[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监控和集群版管理. 移动端和机顶盒的远程通 ...
随机推荐
- 排序算法之直接插入排序Java实现
排序算法之直接插入排序 舞蹈演示排序: 冒泡排序: http://t.cn/hrf58M 希尔排序:http://t.cn/hrosvb 选择排序:http://t.cn/hros6e 插入排序: ...
- 洛谷.4252.[NOI2006]聪明的导游(提答 直径 随机化)
题目链接 随机化 暴力: 随便从一个点开始DFS,每次从之前得到的f[i]最大的子节点开始DFS.f[i]为从i开始(之前)能得到的最大答案. 要注意的是f[i]应当有机会从更小的答案更新, 9.10 ...
- 【二分】【预处理】zoj4029 Now Loading!!!
题意:给定一个序列,多次询问 将a数组从小到大排序,下面那个值只有不超过32种,于是预处理f[i][j],表示分母为i时,aj/i的前缀和是多少. 然后对于一个给定的p,一定将分母划分成了一些连续的段 ...
- 课下测试ch17&ch18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
- SQL SERVER 扩展属性的操作方法
将数据库迁移到 Azure SQL 数据库时出现错误,不支持扩展属性“MS_Description”,因此就如何操作扩展属性进行在此记录. 查询扩展属性 SELECT *,OBJECT_NAME(ma ...
- MAC下安装多版本JDK和切换几种方式
环境: MAC AIR,OS X 10.10,64位 历史: 过去 Mac 上的 Java 都是由 Apple 自己提供,只支持到 Java 6,并且OS X 10.7 开始系统并不自带(而是可选 ...
- 【洛谷】4180:【模板】严格次小生成树[BJWC2010]【链剖】【线段树维护最大、严格次大值】
P4180 [模板]严格次小生成树[BJWC2010] 题目描述 小C最近学了很多最小生成树的算法,Prim算法.Kurskal算法.消圈算法等等.正当小C洋洋得意之时,小P又来泼小C冷水了.小P说, ...
- Go语言Web框架gwk介绍 (五)
Session Go的net/http本身不带session的机制,需要开发人员自行实现,gwk实现了内存中的session存储机制,如果需要将session存在其他地方比如redis或者memcac ...
- DataTable添加行的方法
方法一: DataTable tblDatas = new DataTable("Datas");DataColumn dc = null;dc = tblDatas.Colum ...
- C# 标签(条码)的打印与设计(二)
上一篇说到条码的打印,主要是通过读取模板定义文件(XML文件),然后结合从数据库中读取的动态数据结合而产生条码.下面主要说一下如何设计这个条码模板.设计过程也很简单,只需要简单的拖拉即可.然后点击小箭 ...