先贴代码:
const Koa = require("koa");
const cluster = require("cluster");
const numCPUs = require("os").cpus().length;
if (cluster.isMaster) {
console.log(`主进程 ${process.pid} 正在运行`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
const app = new Koa();
app.use(async ctx => {
const time = parseInt(new Date().getTime() / 1000);
await new Promise(resolve => setTimeout(resolve, 10 * 1000));
ctx.body = `[${process.pid}] time: ${time}`;
});
app.listen(3000);
console.log(`工作进程 ${process.pid} 已启动`);
}
用 await new Promise(resolve => setTimeout(resolve, 10 * 1000)); 阻塞请求,模拟耗时操作(调用第三方接口)。
手工测试:浏览器开三个标签页,看 进程号不同 并且 时间戳刚刚好都是差10秒。
ab 测试:ab -n 30 -c 10 http://127.0.0.1:3000/ 在测试修改进程数量对结果没有影响。
求大神解答。