Nodejs集群仅使用1个worker

时间:2017-02-12 16:27:12

标签: node.js node-modules node-cluster

为什么群集模块只使用1-2名工作人员并且不会通过所有12名工作人员平衡负载?网站统计:每日10000个用户,100-200个在线用户不断。我正在使用nginx和pm2来启动服务器。

屏幕截图:Ubuntu 14.04 top command

我的代码:

let net = require('net'),
config = require('config'),
cluster = require('cluster'),
logger = require('packages/logger'),
os = require('os');

if(cluster.isMaster) {
let workers = [], workersCount = process.env.NODE_ENV === 'production' ? os.cpus().length : 4;
let spawn = function(i) {
    workers[i] = cluster.fork();
    workers[i].on('exit', () => {
        logger.error(`Worker ${i} is down`);
        spawn(i);
    });
};
for (let i = 0; i < workersCount; i++) {
    logger.debug(`Spawn worker №${++workers.length}`);
    spawn(i);
}
let worker_index = function(ip, len) {
    let s = '';
    for (let i = 0, _len = ip.length; i < _len; i++) {
        if (!isNaN(ip[i])) {
            s += ip[i];
        }
    }
    return Number(s) % len;
};
net.createServer({pauseOnConnect: true}, (connection) => {
    let worker = workers[worker_index(connection.remoteAddress, workersCount)];
    worker.send('sticky-session:connection', connection);
}).listen(config.default.http.port);

}else {
let server = require('config/server');
server = server.server;//just an express http server

process.on('message', (message, connection) => {
    if (message !== 'sticky-session:connection') {
        return;
    }
    server.emit('connection', connection);
    connection.resume();
});
}

0 个答案:

没有答案