Let's see how to do load balancing in Node.js.

Before we start with the solution, you can do a test to see the ability concurrent requests your current machine can handle.

This is our server.js:

const http = require('http');
const pid = process.pid;
// listen the mssage event on the global
// then do the computation
process.on('message', (msg) => {
const sum = longComputation();
process.send(sum);
}) http.createServer((req, res) => {
for (let i = ; i<1e7; i++); // simulate CPU work
res.end(`Handled by process ${pid}`)
}).listen(, () => {
console.log(`Started process ${pid}`);
})

Test 200 concurrent requests in 10 seconds.

ab -c200 -t10 http:localhost:/

For one single node server can handle 51 requsts / second:

Create cluster.js:

// Cluster.js
const cluster = require('cluster');
const os = require('os'); // For runing for the first time,
// Master worker will get started
// Then we can fork our new workers
if (cluster.isMaster) {
const cpus = os.cpus().length; console.log(`Forking for ${cpus} CPUs`);
for (let i = ; i < cpus; i++) {
cluster.fork();
}
} else {
require('./server');
}

For the first time Master worker is running, we just need to create as many workers as our cpus allows. Then next run, we just require our server.js; that's it! simple enough!

Running:

node cluster.js

When you refresh the page, you should be able to see, we are assigned to different worker.

Now, if we do the ab testing again:

ab -c200 -t10 http:localhost:/

The result is 181 requests/second!


Sometimes it would be ncessary to communcation between master worker and cluster wokers.

Cluster.js:

We can send information from master worker to each cluster worker:

const cluster = require('cluster');
const os = require('os'); // For runing for the first time,
// Master worker will get started
// Then we can fork our new workers
if (cluster.isMaster) {
const cpus = os.cpus().length; console.log(`Forking for ${cpus} CPUs`);
for (let i = ; i < cpus; i++) {
cluster.fork();
} console.dir(cluster.workers, {depth: });
Object.values(cluster.workers).forEach(worker => {
worker.send(`Hello Worker ${worker.id}`);
})
} else {
require('./server');
}

In the server.js, we can listen to the events:

const http = require('http');
const pid = process.pid;
// listen the mssage event on the global
// then do the computation
process.on('message', (msg) => {
const sum = longComputation();
process.send(sum);
}) http.createServer((req, res) => {
for (let i = ; i<1e7; i++); // simulate CPU work
res.end(`Handled by process ${pid}`)
}).listen(, () => {
console.log(`Started process ${pid}`);
}) process.on('message', msg => {
console.log(`Message from master: ${msg}`)
})

A one patical example would be count users with DB opreations;

// CLuster.js

const cluster = require('cluster');
const os = require('os');
/**
* Mock DB Call
*/
const numberOfUsersDB = function() {
this.count = this.count || ;
this.count = this.count * this.count;
return this.count;
} // For runing for the first time,
// Master worker will get started
// Then we can fork our new workers
if (cluster.isMaster) {
const cpus = os.cpus().length; console.log(`Forking for ${cpus} CPUs`);
for (let i = ; i < cpus; i++) {
cluster.fork();
} const updateWorkers = () => {
const usersCount = numberOfUsersDB();
Object.values(cluster.workers).forEach(worker => {
worker.send({usersCount});
});
} updateWorkers();
setInterval(updateWorkers, );
} else {
require('./server');
}

Here, we let master worker calculate the result, and every 10 seconds we send out the result to all cluster workers.

Then in the server.js, we just need to listen the request:

let usersCount;
http.createServer((req, res) => {
for (let i = ; i<1e7; i++); // simulate CPU work
res.write(`Users ${usersCount}`);
res.end(`Handled by process ${pid}`)
}).listen(, () => {
console.log(`Started process ${pid}`);
}) process.on('message', msg => {
usersCount = msg.usersCount;
})

[Node.js] Load balancing a Http server的更多相关文章

  1. Node.js 从零开发 web server博客项目[express重构博客项目]

    web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...

  2. Node.js 从零开发 web server博客项目[数据存储]

    web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...

  3. Node.js 从零开发 web server博客项目[koa2重构博客项目]

    web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...

  4. Node.js 从零开发 web server博客项目[安全]

    web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...

  5. Node.js 从零开发 web server博客项目[日志]

    web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...

  6. Node.js 从零开发 web server博客项目[登录]

    web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...

  7. Node.js 从零开发 web server博客项目[接口]

    web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...

  8. Node.js 从零开发 web server博客项目[项目介绍]

    web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...

  9. 利用Node.js对某智能家居server重构

    原文摘自我的前端博客,欢迎大家来訪问 http://www.hacke2.cn 之前负责过一个智能家居项目的开发,外包重庆一家公司的.我们主要开发server监控和集群版管理. 移动端和机顶盒的远程通 ...

随机推荐

  1. Codeforces.739E.Gosha is hunting(DP 带权二分)

    题目链接 \(Description\) 有\(n\)只精灵,两种精灵球(高级和低级),每种球能捕捉到第\(i\)只精灵的概率已知.求用\(A\)个低级球和\(B\)个高级球能捕捉到精灵数的最大期望. ...

  2. 【BFS】【最小生成树】Petrozavodsk Winter Training Camp 2018 Day 1: Jagiellonian U Contest, Tuesday, January 30, 2018 Problem G. We Need More Managers!

    题意:给你n个点,点带权,任意两点之间的边权是它们的点权的异或值中“1”的个数,问你该图的最小生成树. 看似是个完全图,实际上有很多边是废的.类似……卡诺图的思想?从读入的点出发BFS,每次只到改变它 ...

  3. ngx_lua应用最佳实践

    引子: 以下文字,是UPYUN系统开发工程师timebug在SegmentFault D-Day南京站技术沙龙上所做分享的内容要义提炼,主题为UPYUN系统开发团队在进行业务逻辑由C模块到ngx_lu ...

  4. 如何成为一名优秀的CTO(首席技术官)

    最近我发现很多开发人员都表示不知道如何规划职业生涯的下一个步骤.基于我们目前所处的科技泡沫现象,很多工程师都倾向于留在大型的成熟公司,或者要么a)去初创企业工作要么b)自己搞初创公司. 回顾我自己的职 ...

  5. [POJ1082]Calendar Game

    题目大意: 日历上博弈,从给定的日期,按照下述规则跳转日期: 1.跳到第二天: 2.调到下个月相同的日期(如果没有就不能跳转). 刚刚好跳到2001年11月4日的人胜,跳转时不能跳到2001年11月4 ...

  6. Java混剪音频

    分享一个之前看过的程序,可以用来剪辑特定长度的音频,将它们混剪在一起,思路如下: 1.使用 FileInputStream 输入两个音频 2.使用 FileInputStream的skip(long ...

  7. service redis does not support chkconfig 的解决办法

    问题解决办法如下: 必须把下面两行注释放在/etc/init.d/redis文件靠前的注释中(加入以下注释): # chkconfig: # description: Redis is a persi ...

  8. Oracle常见的查询代码

    /** * 分页查询 */ int currentPage=3;//当前页码 int pageSize=5;//每页的记录条数 String sql=" select * from &quo ...

  9. DEX 可视化查阅

    参考: http://bbs.pediy.com/thread-208828.htm 010 Editor 下载地址: http://www.sweetscape.com/download/ //-- ...

  10. 用swift开发仪表盘控件(一)

    苹果swift刚刚推出不久,接触到这个语言是一个偶然的机会,无聊之余随便看了下它的语法: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveW5tYW95b2 ...