[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 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的更多相关文章
- Node.js 从零开发 web server博客项目[express重构博客项目]
web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...
- Node.js 从零开发 web server博客项目[数据存储]
web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...
- Node.js 从零开发 web server博客项目[koa2重构博客项目]
web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...
- Node.js 从零开发 web server博客项目[安全]
web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...
- Node.js 从零开发 web server博客项目[日志]
web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...
- Node.js 从零开发 web server博客项目[登录]
web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...
- Node.js 从零开发 web server博客项目[接口]
web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...
- Node.js 从零开发 web server博客项目[项目介绍]
web server博客项目 Node.js 从零开发 web server博客项目[项目介绍] Node.js 从零开发 web server博客项目[接口] Node.js 从零开发 web se ...
- 利用Node.js对某智能家居server重构
原文摘自我的前端博客,欢迎大家来訪问 http://www.hacke2.cn 之前负责过一个智能家居项目的开发,外包重庆一家公司的.我们主要开发server监控和集群版管理. 移动端和机顶盒的远程通 ...
随机推荐
- jQuery学习总结2
六.动画效果 6.1.基本 hide([speed,[fn]])隐藏显示的元素 speed: 三种预定速度之一的字符串("slow","normal", or ...
- Codeforces.724G.Xor-matic Number of the Graph(线性基)
题目链接 \(Description\) 给定一张带边权无向图.若存在u->v的一条路径使得经过边的边权异或和为s(边权计算多次),则称(u,v,s)为interesting triple(注意 ...
- Azure ServiceBus的消息中带有@strin3http//schemas.microsoft.com/2003/10/Serialization/�
今天碰到一个很讨厌的问题,使用nodejs 接收Azure service bus队列消息的时候,出现了:@strin3http//schemas.microsoft.com/2003/10/Seri ...
- Wannafly挑战赛22游记
Wannafly挑战赛22游记 幸运的人都是相似的,不幸的人各有各的不幸. --题记 A-计数器 题目大意: 有一个计数器,计数器的初始值为\(0\),每次操作你可以把计数器的值加上\(a_1,a_2 ...
- TCP的建立和终止 图解
前言 在没有理解TCP连接是如何建立和终止之前,我想你可能并不会使用connect,accept,close这三个函数并且使用netstat程序来调试应用.所以掌握TCP连接的建立和终止势在必行. 三 ...
- python开发_webbrowser_浏览器控制模块
''' python的webbrowser模块支持对浏览器进行一些操作 主要有以下三个方法: webbrowser.open(url, new=0, autoraise=True) webbrowse ...
- BZOJ 1029: [JSOI2007]建筑抢修 优先队列
1029: [JSOI2007]建筑抢修 Time Limit: 4 Sec Memory Limit: 162 MB 题目连接 http://www.lydsy.com/JudgeOnline/p ...
- jquery 图片预加载
/图片无序预加载 (function($){ function Preload(imgs,fns){ this.imgs=(typeof imgs==="string")?[img ...
- TLC2262和TLC2264 轨对轨运算放大器
TLC2262和TLC2264分别是TI公司双路和四路运算放大器,两种器件可以在单电源或双电源条件下供电,从而增强了动态的范围,可以达到轨对轨输出的性能.TLC226X系列与TLC225X的微功耗和T ...
- CNZZ站点流量统计原理简析
这是我的域名www.iyizhan.com.暂无内容,当中仅仅有一个页面index.html. 在index.html上放置了例如以下的 js 脚本: <script src="ht ...