Cluster 模块允许 Node.js 利用多核系统,提高应用程序性能。让我们探讨一下如何有效地使用它。
const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { console.log(`Master ${process.pid} is running`); // Fork workers for (let i = 0; i { console.log(`Worker ${worker.process.pid} died`); }); } else { // Workers can share any TCP connection http.createServer((req, res) => { res.writeHead(200); res.end('Hello World\n'); }).listen(8000); console.log(`Worker ${process.pid} started`); }
Node.js 使用循环方法自动处理负载平衡。
if (cluster.isMaster) { const worker = cluster.fork(); worker.send('Hi there'); } else { process.on('message', (msg) => { console.log('Message from master:', msg); }); }
if (cluster.isMaster) { cluster.on('exit', (worker, code, signal) => { if (!worker.exitedAfterDisconnect) { console.log('Worker crashed. Starting a new worker'); cluster.fork(); } }); process.on('SIGUSR2', () => { const workers = Object.values(cluster.workers); const restartWorker = (workerIndex) => { const worker = workers[workerIndex]; if (!worker) return; worker.on('exit', () => { if (!worker.exitedAfterDisconnect) return; console.log(`Exited process ${worker.process.pid}`); cluster.fork().on('listening', () => { restartWorker(workerIndex 1); }); }); worker.disconnect(); }; restartWorker(0); }); }
集群模块对于水平扩展非常强大,但要谨慎使用。始终进行分析以确保它能够解决您的特定性能需求。
干杯?
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3