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. BZOJ 4605 崂山白花蛇草水(权值线段树+KD树)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=4605 [题目大意] 操作 1 x y k 表示在点(x,y)上放置k个物品, 操作 2 ...

  2. SB!SB!SB! ----WriteUp

    原题 下载图片 http://ctf5.shiyanbar.com/stega/ste.png 用Stegsolve查看 发现有个二维码 扫码可以知道flag

  3. SLF4J versions 1.4.0 and later requires log4j 1.2.12 or later 终极解决

    http://blog.sina.com.cn/s/blog_54eb26870100uynj.html 到SLF4J官方网站:http://www.slf4j.org/codes.html#log4 ...

  4. 【BZOJ】2760: [JLOI2011]小A的烦恼【字符串模拟】

    2760: [JLOI2011]小A的烦恼 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 406  Solved: 258[Submit][Statu ...

  5. hdu 3061 最大权闭合子图

    属于模板题吧... #include <cstdio> #include <cstring> #include <vector> #define min(a,b) ...

  6. bzoj 2844 子集异或和名次

    感谢: http://blog.sina.cn/dpool/blog/s/blog_76f6777d0101d0mr.html 的讲解(特别是2^(n-m)的说明). /*************** ...

  7. jconsole监控上Linux上的JVM

    说明: 首先JConsole这个是JDK里面自带的工具  在JAVA_HOME/bin目录下,今天主要测试远程监控JVM 第一步:设置好需要远程机器的Tomcat 修改Tomcat下的配置文件:/us ...

  8. centos7安装kafka_2.11-1.0.0 新手入门

    系统环境 1.操作系统:64位CentOS Linux release 7.2.1511 (Core) 2.jdk版本:1.8.0_121 3.zookeeper版本:zookeeper-3.4.9. ...

  9. weblogic部署异常: cvc-enumeration-valid: string value '3.0' is not a valid enumeration value for web-app-versionType in namespace http://java.sun.com/xml/ns/javaee:<null>

    尝试使用weblogic部署一个Demo应用,在选择应用目录后,报出下面的异常: VALIDATION PROBLEMS WERE FOUND problem: cvc-enumeration-val ...

  10. redhat 6.6 安装 (LVM)

    http://www.cnblogs.com/kerrycode/p/4341960.html