Skip to content

Instantly share code, notes, and snippets.

@theharveyz
Last active December 6, 2016 07:24
Show Gist options
  • Save theharveyz/4a263b8dbdfb6e23ee2cba78ef8ccea2 to your computer and use it in GitHub Desktop.
Save theharveyz/4a263b8dbdfb6e23ee2cba78ef8ccea2 to your computer and use it in GitHub Desktop.
使用cluster模块实现负载均衡,和多进程监听同一端口
import http from 'http';
import cluster from 'cluster';
import os from 'os';
const port = 3001;
// cpu核数
const numCpus = os.cpus().length;
console.log(`The num of cpu: ` + numCpus);
// 实现Load balancer
if (cluster.isMaster) {
console.log(`[MASTER],PID:${process.pid}, STARTING...`);
for (var i = 0; i < numCpus; i++) {
cluster.fork();
}
cluster.on('listening', (worker, address) => {
console.log(`listening... worker:${worker.id}, address:${address.port},
worker pid: ${worker.process.pid}`);
});
cluster.on('fork', (...args) => {
console.log(args);
});
cluster.on('exit', (worker, code, signal) => {
console.log(`worker die... worker:${worker.id}, code:${code},
signal: ${signal}`);
// 注意:如果子进程worker抛出异常,则会触发该worker退出
// 需要重新fork
cluster.fork();
});
} else {
console.log(`[WORKER${cluster.worker.id}] STARTING...`);
http.createServer((req, res) => {
res.writeHead(200);
res.end(`WorkerId:${cluster.worker.id},Pid:${cluster.worker.process.pid}`);
}).listen(port || process.env.PORT);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment