主线程就是当前运行的js文件,主线程根据你本机系统的核数来创建子进程。所有进程共享一个监听端口8000,当有请求发起时,主线程会将该请求随机分配给某个子进程。console.log(‘Worker #’ + cluster.worker.id + ‘ make a response’);这句代码可以打印出是哪个进程处理该请求。
const { cpus } = require("os")
const cluster = require("cluster")
let cpuNum = cpus().length
const http = require("http")
let worker;
if (cluster.isMaster) {
console.log(`主进程${process.pid}正在运行`)
//衍生工作进程
for (let i = 0; i < cpuNum; i++) {
worker= cluster.fork()
worker.send("ahha")//父往子传参
worker.on("message",data=>{ //子进程传过来的数据
console.log(data)
})
}
cluster.on('listening', function (worker, address) {
console.log('listening: worker' + worker.id + ',pid:' + worker.process.pid + ', Address:' + address.address + ":" + address.port);
});
cluster.on("exit",(worker,code,signal)=>{
console.log(`工作进程${worker.process.pid}已退出`)
// cluster.fork()
})
}else{
//工作进程可以共享任何TCP连接
//共享的是HTTP服务器
http.createServer((req,res)=>{
res.writeHead(200);
res.end("你好世界\n")
}).listen(8080)
process.on("message",data=>{//父进程传过来的数据
console.log(data)
})
process.send("ahha") //子进程往父进程传参
//console.log(`工作进程${process.pid}已启动`)
}