Node的cluster模块详解

cluster是node的内置模块,用来nodeJs多核多进程处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const cluster = require('cluster'); //多核处理模块
const os = require('os'); //系统模块
const http = require('http'); 自建服务器模块

const cpuLen = os.cpus().length;

if(cluster.isMaster) { //是否是主进程(master)
Object.keys(cpuLen).forEach(() => {
const worker = cluster.fork(); //创建子进程
worker.send('i am worker' + worker.id) //向子进程发送消息(由主控来调用)
});

cluster.on('listening',(worker,address) => {
console.log('监听子进程向主控的状态改变: ' + worker.id + address.id);
});
cluster.on('online',(worker) => {
console.log('监听子进程创建成功,id: ' + worker.id);
});
cluster.on('disconnect',(worker) => {
console.log('监听子进程断线事件,id: ' + worker.id);
});
cluster.on('exit',(worker) => {
console.log('监听子进程离开事件,id: ' + worker.id);
});

} else if(cluster.isWorker) { //是否是子进程(worker)
process.on('message',(msg) => {
console.log('master传来的消息: ' + msg); //监听主控发来的消息
process.send('hello i am worker' + cluster.worker.id);
});
http.createServer((req,res) => {
res.writeHead(200,{'Content-type','text/html'});
res.end('worker.id: ' + cluster.worker.id + 'worker.pid:' + process.pid);
})
}
文章目录
,
//