Skip to content

集群

import os from "node:os";
import cluster from "node:cluster";
import http from "node:http";
console.log(os.cpus().length); // 获取cpu核数
const cpuNum = os.cpus().length;
if (cluster.isPrimary) {
// 主进程
console.log(`Primary process ${process.pid} is running`);
for (let i = 0; i < cpuNum; i++) {
cluster.fork();
}
} else {
// 子进程
console.log(`Worker process ${process.pid} is running`);
http
.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Hello World from ${process.pid}`);
})
.listen(3000, () => {
console.log(`Worker process ${process.pid} is running`);
});
}
// 可以在终端中使用 ps node 查看进程
// 压测 50000次请求,1000个并发
// npx loadtest http://localhost:3000 -n 50000 -c 1000