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:

  1. var cluster = require('cluster');
    var http = require('http');
    var numCPUs = require('os').cpus().length;
  2. if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
    }
  3. 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\n");
    }).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.

How Node.js Multiprocess Load Balancing Works的更多相关文章

  1. 【架构】How To Use HAProxy to Set Up MySQL Load Balancing

    How To Use HAProxy to Set Up MySQL Load Balancing Dec  2, 2013 MySQL, Scaling, Server Optimization U ...

  2. How Network Load Balancing Technology Works--reference

    http://technet.microsoft.com/en-us/library/cc756878(v=ws.10).aspx In this section Network Load Balan ...

  3. [zz] pgpool-II load balancing from FAQ

    It seems my pgpool-II does not do load balancing. Why? First of all, pgpool-II' load balancing is &q ...

  4. Network Load Balancing Technical Overview--reference

    http://technet.microsoft.com/en-us/library/bb742455.aspx Abstract Network Load Balancing, a clusteri ...

  5. [Node.js] Load balancing a Http server

    Let's see how to do load balancing in Node.js. Before we start with the solution, you can do a test ...

  6. Node.js Web 开发框架大全《中间件篇》

    这篇文章与大家分享优秀的 Node.js 中间件模块.Node 是一个服务器端 JavaScript 解释器,它将改变服务器应该如何工作的概念.它的目标是帮助程序员构建高度可伸缩的应用程序,编写能够处 ...

  7. A chatroom for all! Part 1 - Introduction to Node.js(转发)

    项目组用到了 Node.js,发现下面这篇文章不错.转发一下.原文地址:<原文>. ------------------------------------------- A chatro ...

  8. Node.js Tools 1.2 for Visual Studio 2015 released

    https://blogs.msdn.microsoft.com/visualstudio/2016/07/28/node-js-tools-1-2-visual-studio-2015/ What ...

  9. Understanding Asynchronous IO With Python 3.4's Asyncio And Node.js

    [转自]http://sahandsaba.com/understanding-asyncio-node-js-python-3-4.html Introduction I spent this su ...

随机推荐

  1. 【Python网络编程】多线程聊天软件程序

    课程设计的时候制作的多线程聊天软件程序 基于python3.4.3 import socket import pickle import threading import tkinter import ...

  2. python安装第三方包的两种方式

    最近研究QQ空间.微博的(爬虫)模拟登录,发现都涉及RSA算法.于是需要下一个RSA包(第三方包).折腾了很久,主要是感觉网上很多文章对具体要在哪里操作写得不清楚.这里做个总结,以免自己哪天又忘了. ...

  3. LeetCode_Jump Game II

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  4. Http响应报文

    HTTP响应也由三个部分组成,分别是:状态行.消息报头.响应正文. 其中,HTTP-Version表示服务器HTTP协议的版本:Status-Code表示服务器发回的响应状态代码:Reason-Phr ...

  5. JavaScript为unicode编码转换为中文

    代码laycode - v1.1 关于这样的数据转换为中文问题,常用的以下方法. 1. eval解析或new Function("'+ str +'")()  str = eval ...

  6. jQuery中append html后绑定事件不起作用

    事件一定要紧跟append之后, 否则append元素点击不起作用 $(function(){$('div').append('<ul><li id="appli" ...

  7. javascript代码混淆原理

    https://www.google.com/search?biw=1440&bih=729&q=javascript%E4%BB%A3%E7%A0%81%E6%B7%B7%E6%B7 ...

  8. linux 挂载 镜像文件

    挂接命令(mount) 命令格式: mount [-t vfstype] [-o options] device dir 其中: 1.-t vfstype指定文件系统的类型,通常不必指定.mount会 ...

  9. 网易云课堂_C++开发入门到精通_章节7:模板

    课时35类模板 类模板 创建类模板的实例 class Name<类型参数表>object; 类模板与模板类的区别 类模板是模板的定义,不是一个实实在在的类,定义中用到通用类型参数 模板类是 ...

  10. Python递归函数与斐波那契数列

    定义:在函数内部,可以调用其他函数.如果一个函数在内部调用自身本身,这个函数就是递归函数. 阶乘实例 n = int(input(">>:")) def f(n): s ...