const cluster = require('cluster')const http = require('http')const { cpus } = require('os')const numCPUs = cpus().lengthif (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 runningWorker 25021 startedWorker 25022 startedWorker 25024 startedWorker 25023 startedWorker 25025 startedWorker 25027 startedWorker 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)}