关于该模块的功能,源文档描述如此“A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load.” 其意就是:Node的示例以单进程的模式运行,有时为了充分利用多核系统的资源用户需要运行一组Node进程来分担负载。
Cluster用法介绍
首先贴出一段该模块示例应用代码,接下来进行详细分析,代码如下:
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
require('os').cpus().forEach(function(){
cluster.fork();
});
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
cluster.on('listening', function(worker, address) {
console.log("A worker with #"+worker.id+" is now connected to " +
address.address +
":" + address.port);
});
} else {
http.createServer(function(req, res) {
res.writeHead(200);
res.end("hello world\n");
console.log('Worker #' + cluster.worker.id + ' make a response');
}).listen(8000);
}
这段代码很简单,主线程就是当前运行的js文件,主线程根据你本机系统的核数来创建子进程。所有进程共享一个监听端口8000,当有请求发起时,主线程会将该请求随机分配给某个子进程。console.log('Worker #' + cluster.worker.id + ' make a response');这句代码可以打印出是哪个进程处理该请求。