Node.js: 多核 CPU 并发运行
本文档属于Node.js 快速部署指南指南的一部分。您可以在此处查看完整指南:快速安全地在 Stackhero 上部署 Node.js。
👋 欢迎查阅 Stackhero 文档!
Stackhero 提供即开即用的 Node.js 云环境,助您高效开发:
- 只需一次简单的
git push,几秒钟即可部署到生产环境,无需额外工具或手动配置。- 支持自定义域名,并自动配置 HTTPS 证书,让您的应用安全无忧,无需额外设置。
- 自动备份、一键升级以及可预测的定价,让您专注于功能开发,基础设施交由 Stackhero 托管。
- 基于专属私有基础设施,保障性能稳定与高水平安全。
节省时间,降低运维负担:只需几分钟,您的应用即可在 Stackhero 的 Node.js 云主机 上运行。
默认情况下,Node.js 只使用单核。若需充分利用所有 CPU 核心,可使用 Node.js 的 cluster API。详细用法请参考 官方 Node.js cluster 文档。
以下为简单示例:
const cluster = require('cluster');
const http = require('http');
const cpusCount = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// 创建 worker 进程
for (let i = 0; i < cpusCount; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
} else {
// worker 共享所有 TCP 连接,此处为 HTTP 服务
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}