用NodeJS實(shí)現(xiàn)集群計(jì)算
Node的單個(gè)實(shí)例運(yùn)行在單個(gè)的線程中,要充分利用多核系統(tǒng),我們可以運(yùn)行Node進(jìn)程集群來(lái)處理負(fù)載。也就是說(shuō),如果系統(tǒng)有8核,單個(gè)Node實(shí)例只能使用其中1核,可以利用cluster包的workers概念來(lái)充分利用所有的核。有趣的是,它們可以共享同一個(gè)端口。
該模塊還處于實(shí)驗(yàn)階段。
- 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);
- }
在一個(gè)4核的計(jì)算機(jī)上,輸出如下:
- 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
posted on 2012-10-10 10:50 你爸是李剛 閱讀(275) 評(píng)論(0) 編輯 收藏