阅读 58

node cluster

关键字: cluster 集群 守护进程 PM2 IPC通信

node用单进程,单线程容错率低,挂掉会直接被用户感知,多核cpu利用率低。

于是引入了多进程。给每个cpu内核分配一个进程。node cluster用来做这件事,它的底层是对child_process 的封装。

fork() creates a new process by duplicating the calling process. The new process is referred to as the child process. The calling process is referred to as the parent process.

The child process and the parent process run in separate memory spaces. At the time of fork() both memory spaces have the same content. Memory writes, file mappings (mmap(2)), and unmappings (munmap(2)) performed by one of the processes do not affect the other.

let cluster = require('cluster');
let http = require('http');
let numCPUs = require("os").cpus().length;
 
if (cluster.isMaster) {
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }
} else {
    http.createServer(function(req, res) {
        res.writeHead(200);
        res.end('process ' + process.pid + ' says hello!');
    }).listen(8000);
}
复制代码

我们创建了多个web服务器实例,并且共用了8000这一个端口,在访问的接口的时候,Cluster会用自己的负载均衡算法,将请求交给子进程处理。

进程守护

有进程退出时,重新fork一个进程,maskter 进程充当了守护进程的作用,所以一定要够健壮。

cluster.on('exit', function(worker, code, signal) {
    console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
    console.log('Starting a new worker');
    cluster.fork();
});
复制代码

PM2能够做到仅仅配置,而不需要改动我们的代码,就帮我们实现多进程启动。

安装了PM2之后,将启动程序的命令改为:pm2 start app.js -i 8,这样PM2就能用上CPU的8个核来跑我们的Node应用。但是PM2无法保证状态服务在进程意外退出的时候(session等)保留,所以需要自己用cluster来管理多进程。

参考: toutiao.io/posts/9k766…

文章分类
后端
文章标签