const cluster = require('cluster')
const http = require('http')
const { cpus } = require('os')
const numCPUs = cpus().length
if (cluster.isPrimary) {
console.log(`Primary ${process.pid} is running`)
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork()
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`)
})
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200)
res.end('hello world\n')
}).listen(8000)
console.log(`Worker ${process.pid} started`)
}
/* 会自动重新执行自身
Primary 25020 is running
Worker 25021 started
Worker 25022 started
Worker 25024 started
Worker 25023 started
Worker 25025 started
Worker 25027 started
Worker 25026 started
*/
const cluster = require('cluster')
const http = require('http')
const { cpus } = require('os')
if (cluster.isPrimary) {
// Keep track of http requests
let numReqs = 0
setInterval(() => {
console.log(`numReqs = ${numReqs}`)
}, 1000)
// Count requests
function messageHandler (msg) {
if (msg.cmd && msg.cmd === 'notifyRequest') {
numReqs += 1
}
}
// Start workers and listen for messages containing notifyRequest
const numCPUs = cpus().length
for (let i = 0; i < numCPUs; i++) {
cluster.fork()
}
for (const id in cluster.workers) {
cluster.workers[id].on('message', messageHandler)
}
} else {
// Worker processes have a http server.
http.Server((req, res) => {
res.writeHead(200)
const pid = process.pid
res.end('process.pid' + pid)
// Notify primary about the request
process.send({ cmd: 'notifyRequest' })
}).listen(3000)
}
上一篇:child_process
下一篇:AbortController