nodejs cluster测试
发布于 2年前 作者 zaobao 2869 次浏览

在双核上开两个worker,阻塞一个worker后,其他worker也被阻塞了。开10个worker也一样,是我cpu核心太少吗?还是本来就这样。

连续发送两个请求,只有一个核是100%,并且从输出看只有一个节点在工作:

A worker with #1 is now connected to 0.0.0.0:8000
A worker with #2 is now connected to 0.0.0.0:8000
Worker #1 has a request
Worker #1 make a response
Time: 5000ms
Worker #1 has a request
Worker #1 make a response
Time: 5001ms

脚本文件: 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) {
    console.log('Worker #' + cluster.worker.id + ' has a request');
    res.writeHead(200);
    console.time('Time');
    function sleep(milliSeconds) {
      var startTime = new Date().getTime();
      while (new Date().getTime() < startTime + milliSeconds);
    }
    sleep(5000);
    res.end("hello world\n");
    console.log('Worker #' + cluster.worker.id + ' make a response');
    console.timeEnd('Time');
  }).listen(8000);
}
8 回复

我的四核,两个核用到了。

C:\dev\test\node-module\cluster>node test.js
cpu#:4
cpu#:4
A worker with #1 is now connected to 0.0.0.0:8000
cpu#:4
A worker with #4 is now connected to 0.0.0.0:8000
cpu#:4
A worker with #3 is now connected to 0.0.0.0:8000
cpu#:4
A worker with #2 is now connected to 0.0.0.0:8000
Worker #2 has a request
Worker #2 make a response
Time: 5001ms
Worker #2 has a request
Worker #2 make a response
Time: 5000ms
Worker #2 has a request
Worker #2 make a response
Time: 5000ms
Worker #2 has a request
Worker #3 has a request
Worker #2 make a response
Time: 5000ms
Worker #2 has a request
Worker #3 make a response
Time: 5001ms
Worker #3 has a request
Worker #2 make a response
Time: 5000ms
Worker #2 has a request
Worker #3 make a response
Time: 5000ms
Worker #3 has a request
Worker #2 make a response
Time: 5000ms

请参考 http://www.cnblogs.com/tingshuo/archive/2013/01/17/2864280.html

cluster是在并发高的情况下才会充分利用多核

其实,是我测试方式不对

@zaobao 楼主,怎么说?

cluster 的负载均衡做的不好

cluster在window下是不能多核负载均衡,在linux下才会

cluster在node v0.11之前的版本,负载都十分不均衡,目前看来v0.11的 cluster 已经修复了这个问题,期待0.12的稳定版早日release吧…

回到顶部