node.js 的 cluster

在 node.js V0.8 之前的版本,node.js 本身不提供多核多进程处理

V0.8之后的版本,node.js 内置了 cluster 功能

之前的

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n'); 
}).listen(2000, "127.0.0.1"); 
console.log('Server running at http://127.0.0.1:2000/');

启动

$ node app
Server running at http://127.0.0.1:2000/

使用cluster实现多进程

var cluster = require('cluster');
var http=require('http');
var cpu_num = require('os').cpus().length;

if (cluster.isMaster) {
    console.log("==启动主进程==");
    for (var i = 0; i < cpu_num; i++) {
        cluster.fork();
        //根据cpu的数量主进程 fork 了相同数量的子进程出来
    }

    cluster.on('listening',function(worker,address){
        console.log('listening: worker ' + worker.process.pid);
    });

    cluster.on('exit', function(worker, code, signal) {
        console.log('exit worker ' + worker.process.pid + ' died');
    });
} else {
    http.createServer(function (req, res) {
        res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n'); 
    }).listen(2000, "127.0.0.1"); 
    console.log('Server running at http://127.0.0.1:2000/');

启动

$ node app
==启动主进程==
Server running at http://127.0.0.1:2000/
listening: worker 19808
Server running at http://127.0.0.1:2000/
Server running at http://127.0.0.1:2000/
Server running at http://127.0.0.1:2000/
listening: worker 13640
listening: worker 11960
listening: worker 18380
Server running at http://127.0.0.1:2000/
Server running at http://127.0.0.1:2000/
listening: worker 11228
listening: worker 3932
Server running at http://127.0.0.1:2000/
listening: worker 19836
Server running at http://127.0.0.1:2000/
listening: worker 20460

 

posted @ 2020-09-25 14:11  慕尘  阅读(272)  评论(0编辑  收藏  举报