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 @   慕尘  阅读(279)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2015-09-25 Yii2登陆添加验证码
点击右上角即可分享
微信分享提示