如果您有兴趣点击查看这篇文章的同学,肯定有是这方面的需求才会看的,是不是?
我说说去弄明白cluster的理由:因为nodejs是单线程运作的,借助异步提高了并发。但毕竟是单线程,做复杂运算是不行的(很多人是这么说的),在一个多核计算机上,譬如八核电脑,如果是发挥其中一核这岂不是不如意,浪费?所以,node自带了一个cluster模块,实现了多进程实现负载均衡。
留意了一下,简书里也有其他的文章是关于cluster,也是差不多内容的浅谈node中的cluster集群 - 简书,可以多对比对比。
部署代码不错,而且方便,只是想深入探究就很难明白了。
部署:
使用westorm软件新建项目,根目录新建cluster.js (位置根据需求而定,只为测试在根目录)
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log('[master] ' + "start master...");
for (var i = 0; i < numCPUs; i++) {
var wk = cluster.fork();
wk.send('[master] ' + 'hi worker' + wk.id);
}
cluster.on('fork', function (worker) {
console.log('[master] ' + 'fork: worker' + worker.id);
});
cluster.on('online', function (worker) {
console.log('[master] ' + 'online: worker' + worker.id);
});
cluster.on('listening', function (worker, address) {
console.log('[master] ' + 'listening: worker' + worker.id + ',pid:' + worker.process.pid + ', Address:' + address.address + ":" + address.port);
});
cluster.on('disconnect', function (worker) {
console.log('[master] ' + 'disconnect: worker' + worker.id);
});
cluster.on('exit', function (worker, code, signal) {
console.log('[master] ' + 'exit worker' + worker.id + ' died');
});
function eachWorker(callback) {
for (var id in cluster.workers) {
callback(cluster.workers[id]);
}
}
setTimeout(function () {
eachWorker(function (worker) {
worker.send('[master] ' + 'send message to worker' + worker.id);
});
}, 3000);
Object.keys(cluster.workers).forEach(function(id) {
cluster.workers[id].on('message', function(msg){
console.log('[master] ' + 'message ' + msg);
});
});
} else if (cluster.isWorker) {
console.log('[worker] ' + "start worker ..." + cluster.worker.id);
process.on('message', function(msg) {
console.log('[worker] '+msg);
process.send('[worker] worker'+cluster.worker.id+' received!');
});
http.createServer(function (req, res) {
res.writeHead(200, {"content-type": "text/html"});
res.end('worker'+cluster.worker.id+',PID:'+process.pid);
}).listen(3001);
}
app.js中建立主进程及子进程,下面代码为实现部分,如果是主进程就创建子进程,否则创建服务器监听端口,子进程共享同一个端口
var cluster =require('cluster');
var http =require('http');
var numCPUs =require('os').cpus().length;
if (cluster.isMaster) {
console.log('[master] ' +"start master...");
for (var i =0;i
cluster.fork();
}
cluster.on('listening',function (worker, address) {
console.log('[master] ' +'listening: worker' + worker.id +',pid:' + worker.process.pid +', Address:' + address.address +":" + address.port);
});
}else if (cluster.isWorker) {
console.log('[worker] ' +"start worker ..." +cluster.worker.id);
http.createServer(function (req, res) {
console.log('worker'+cluster.worker.id);
res.end('worker'+cluster.worker.id+',PID:'+process.pid);
}).listen(3001);
}
测试结果在win下,失败,全部请求只访问其中一个子进程。在Linux下,访问子进程数均匀