node的 cluster集群可有效的增加应用负载能力
以koa为例,实例化创建一个应用:ESM写法(./server.mjs)
import Koa from 'koa'
export const createServer = (port = 8900) => {
const app = new Koa()
app.use(async ctx => {
ctx.body = 'i am koa'
})
app.listen(port, () => { console.log(`server run on http://localhost:${port}`) })
return app
}
然后部署时以集群部署:ESM写法(./cluster.mjs)
import cluster from 'node:cluster'
import { cpus } from 'node:os'
import { createServer } from './server.mjs'
const cpuNum = cpus().length
if (cluster.isPrimary) {
for(let i = 0; i < cpuNum; i ++) {
cluster.fork()
}
} else {
createServer()
}
本地调试则无需集群:(./dev.mjs)
import { createServer } from './server.mjs'
const app = createServer()