Node.js: 多核 CPU 并发运行

本文件是Node.js 快速部署指南指南的一部分。您可以在这里查看完整指南:快速安全地在 Stackhero 上部署 Node.js。

👋 欢迎来到 Stackhero 文档!

Stackhero 提供即开即用的 Node.js cloud 环境,助您加速开发进程:

  • 几秒钟内部署到生产环境,只需简单的 git push,无需额外工具或手动配置。
  • 支持自定义域名,并自动配置 HTTPS 证书,让您的应用安全无忧,无需额外设置。
  • 自动备份、一键更新以及可预测的定价,让您专注于功能开发,基础设施交由 Stackhero 管理。
  • 基于专属私有基础设施,确保性能稳定和高安全性。

节省时间,降低运维负担:只需几分钟,您的应用即可在 Stackhero 的 Node.js cloud hosting 上运行。

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`);
}