[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监控和集群版管理. 移动端和机顶盒的远程通 ...
随机推荐
- EL表达式和JSTL标准标签库
一.EL表达式 什么是EL表达式 EL(Express Lanuage)表达式可以嵌入在jsp页面内部 减少jsp脚本的编写 EL出现的目的是要替代jsp页面中脚本的编写. EL表达式的作用 EL最主 ...
- POI2018
[BZOJ5099][POI2018]Pionek(极角排序+two pointers) 几个不会严谨证明的结论: 1.将所有向量按极角排序,则答案集合一定是连续的一段. 当答案方向确定时,则一个向量 ...
- 【漏洞预警】Apache ActiveMQ Fileserver远程代码执行漏洞(CVE-2016-3088)
漏洞编码:CVE-2016-3088 实验环境:Linux Apache ActiveMQ版本号:Apache ActiveMQ 5.7.0 ----------------------------- ...
- Java Maven:spring boot + Mybatis连接MySQL,通用mapper的增删改查,映射实现多表查询
1. MySQL自带库test添加表user.role 角色表role 用户表user 2. 添加依赖,配置属性 相关依赖:百度即可,此处略 application.properties spring ...
- 【POJ】1840:Eqs【哈希表】
Eqs Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 18299 Accepted: 8933 Description ...
- Codeforces Round #293 (Div. 2) D. Ilya and Escalator 概率DP
D. Ilya and Escalator time limit per test 2 seconds memory limit per test 256 megabytes input standa ...
- 获取数据库连接对象(线程ThreadLocal)
/** * 负责数据库连接定义的程序类 * 该类可以负责所有操作线程的数据库连接,利用get()方法可以获得连接对象 */ public class DatabaseConnection { priv ...
- unity热更新
Unity3D 学习笔记4 —— UGUI+uLua游戏框架 C#Light 和 uLua的对比第二弹 在Unity中使用Lua脚本:语言层和游戏逻辑粘合层处理 Ulua_toLua_基本案例 Uni ...
- 不同的activity使用bundle对象传值给广播接收器
解决了一下午的问题,广播机制传值,在一个activity中发送广播给广播接收器,使用的是同一个action 在另一个activity中如果也发送广播给同一个广播接收器,使用相同的action,会导致后 ...
- QDAC
QDAC GITHUB: svn://www.qdac.cc/QDAC3 包括QMsgPack\QJson\QWoker...等序列和事件调度控件.