node.js开发笔记——cluster

node.js开发笔记——cluster

node启动的服务是一个进程的,且进程内只有一个线程,这样就只能使用一个核心的算力。

可以使用cluter创建多进程来利用多核心cpu。

创建多个进程

主进程用于创建多个工作进程,服务代码写在工作进程中。

js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const cluster = require('node:cluster')
const os = require('node:os')
const http = require('node:http')

const cpus = os.cpus().length

if (cluster.isMaster) {
console.log(`工作进程${worker.process.pid}已运行`)

// 当前在主进程,通过fork创建多个进程(工作进程)
for (let i = 0; i < cpus; i++) {
cluster.fork()
}

cluster.on('exit', (work, code, signal) => {
console.log(`工作进程${worker.process.pid}已停止`)
})
} else {
// 当前在工作进程,启动服务
http.createServer((req, res) => {
res.writeHead(200)
res.end('hello\n')
})
.listen(3333)
console.log(`工作进程${worker.process.pid}已运行`)
}

评论