</div>
</div>
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
require('os').cpus().forEach(function(){
cluster.fork();
});
// In case the worker dies!
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
// As workers come up.
cluster.on('listening', function(worker, address) {
console.log("A worker with #"+worker.id+" is now connected to " +\
address.address +\
":" + address.port);
});
// When the master gets a msg from the worker increment the request count.
var reqCount = 0;
Object.keys(cluster.workers).forEach(function(id) {
cluster.workers[id].on('message',function(msg){
if(msg.info && msg.info == 'ReqServMaster'){
reqCount += 1;
}
});
});
// Track the number of request served.
setInterval(function() {
console.log("Number of request served = ",reqCount);
}, 1000);
} else {
// Workers can share the same port!
require('http').Server(function(req, res) {
res.writeHead(200);
res.end("Hello from Cluster!");
// Notify the master about the request.
process.send({ info : 'ReqServMaster' });
}).listen(8000);
} </pre><br />
在一個4核的計算機上,輸出如下:
Number of request served = 0
A worker with #2 is now connected to 0.0.0.0:8000
A worker with #4 is now connected to 0.0.0.0:8000
A worker with #1 is now connected to 0.0.0.0:8000
A worker with #3 is now connected to 0.0.0.0:8000
Number of request served = 0
...
Number of request served = 2
..
Number of request served = 4
...
Number of request served = 6
來自:http://blog.csdn.net/chszs/article/details/8054773
本文由用戶
jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!