Skip to content
导航

Cluster

cluster 模块允许轻松创建所有共享服务器端口的子进程。

js
const cluster = require('cluster')
const numCPUs  = require('os').availableParallelism()
const http = require('http');

// windows 系统下,调度策略默认值为SCHED_NONE,即不调度
cluster.schedulingPolicy = cluster.SCHED_RR

if(cluster.isMaster){
  for(let i = 0; i < numCPUs ; i++){
    cluster.fork();
  }
  console.log(`Master ${process.pid} started`);
}else{
  http.createServer(function(req, res){
    res.end(`response from worker ${process.pid}`);
  }).listen(3000);

  console.log(`Worker ${process.pid} started`);
}

创建一个shell脚本测试负载均衡效果

sh
#!/bin/bash

# req.sh
for((i=1;i<=4;i++)); do   
  curl http://127.0.0.1:3000
  echo ""
done

参考资料