Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

cluster 集群

基础

源代码:lib/cluster.js

作用:创建共享服务器端口的子进程,利用多核CPU处理负载

用法

  • 引入

    • es6
      import cluster from 'cluster';
      
    • commonjs
      const cluster = require('cluster')
      

负载均衡

这里用的是CommonJS,请使用<=14版本的nodejs

server.js

const http = require('http');
const pid = process.pid;
http.createServer((req, res) => {
    for(let i=0;i<1e7;i++) {} // 模拟CPU工作
    res.end(`handled by process.${pid}`);
}).listen(8080, () => {
    console.log(`started process`, pid);
});

单进程运行

node server.js

可以使用apache的基准测试工具,测试单线程的响应情况

ab -c 200 -t 10 http://localhost:8080/

这里代表每10秒发送200个并发请求

cluster.js

const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
    const cpus = os.cpus().length;
    console.log('forking for ', cpus, ' CPUS');
    for(let i = 0;i<cpus;i++) {
        cluster.fork();
    }
} else {
    requre('./server.js');
}

多进程运行

node cluster.js