用NodeJS實現叢集計算

來源:互聯網
上載者:User
Node的單個執行個體運行在單個的線程中,要充分利用多核系統,我們可以運行Node進程叢集來處理負載。

也就是說,如果系統有8核,單個Node執行個體只能使用其中1核,可以利用cluster包的workers概念來充分利用所有的核。有趣的是,它們可以共用同一個連接埠。

該模組還處於實驗階段。

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);}

在一個4核的電腦上,輸出如下:

Number of request served =  0A worker with #2 is now connected to 0.0.0.0:8000A worker with #4 is now connected to 0.0.0.0:8000A worker with #1 is now connected to 0.0.0.0:8000A worker with #3 is now connected to 0.0.0.0:8000Number of request served =  0...Number of request served =  2..Number of request served =  4...Number of request served =  6

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.