zoukankan      html  css  js  c++  java
  • How Node.js Multiprocess Load Balancing Works

    As of version 0.6.0 of node, load multiple process load balancing is available for node. The concept of forking and child processes isn't new to me. Yet, it wasn't obvious to me how this was implemented at first. It's quite easy to use however:


    var cluster = require('cluster');
    var http = require('http');
    var numCPUs = require('os').cpus().length;

    if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
    }

    cluster.on('death', function(worker) {
    console.log('worker ' + worker.pid + ' died');
    });
    } else {
    // Worker processes have a http server.
    http.Server(function(req, res) {
    res.writeHead(200);
    res.end("hello world ");
    }).listen(8000);
    }
    This is quite a beautiful api, but it hides some clever details. For instance, how is possible for all child processes to each open up port 8000 and start listening?
     
    The answer is that the cluster module is just a wrapper around child_process.fork and net.Server.listen is aware of the cluster module. Specifically, cluster.fork uses child_process.fork to create child processes with special variable set in their environments to indicate cluster was used. Specifically process.env.NODE_WORKER_ID is non-zero for such children.
     
    envCopy['NODE_WORKER_ID'] = id;
    var worker = fork(workerFilename, workerArgs, { env: envCopy });
     
    Then net.Server.listen checks to see if process.env.NODE_WORKER_ID is set. If so, then the current process is a child created cluster. Instead of trying to start accepting connections on this port, a file handle is requested from the parent process:
     


    //inside net.js
    require('cluster')._getServer(address, port, addressType, function(handle) {
    self._handle = handle;
    self._listen2(address, port, addressType);
    });
     
    //inside cluster.js
    cluster._getServer = function(address, port, addressType, cb) {
    assert(cluster.isWorker);
     
    queryMaster({
    cmd: "queryServer",
    address: address,
    port: port,
    addressType: addressType
    }, function(msg, handle) {
    cb(handle);
    });
    };
     
    Finally, this handle is listened on instead of creating a new handle. At which point you have another process that is listening on the same port. Quite clever, though I think the beauty of the api comes at the cost of some not so hideous hacks inside the api.
  • 相关阅读:
    Leetcode 58. 最后一个单词的长度 双指针
    Leetcode 125. 验证回文串 双指针
    拜托,大厂做项目可不简单!
    被问懵了:一个进程最多可以创建多少个线程?
    面对祖传屎山代码应该采用的5个正确姿势
    VUE代码格式化配置vetur、eslint、prettier的故事
    如何快速实现一个虚拟 DOM 系统
    NodeJS 进程是如何退出的
    [堆][启发式合并]luogu P3261 [JLOI2015]城池攻占
    [Trie][堆]luogu P5283 [十二省联考2019]异或粽子
  • 原文地址:https://www.cnblogs.com/huenchao/p/6218827.html
Copyright © 2011-2022 走看看