node cluster模块的使用和测试
首先安装async包
用到的有http、cluster包
http和cluster都会node自带的包,无需安装
1:创建cluster.js,代码如下,更具cpu创建多个进程
var cluster = require("cluster");
var http = require("http");
var numCPUs = require('os').cpus().length;
if(cluster.isMaster){
console.log("[master] " + "start master......");
var data = 0;
for(var i=0; i<numCPUs; i++){
var work_process = cluster.fork();
}
cluster.on("listening", function(worker, address){
console.log("[master] " + "listening: worker "+worker.id + ", pid:"+worker.process.pid + ",Address:" + address.address + ":" + address.port);
});
cluster.on("exit", function(worker, code, signal){
console.log('worker ' + worker.process.pid + ' died');
});
}else{
http.createServer(function(req, res){
console.log("worker" + cluster.worker.id);
res.end("worker" + cluster.worker.id);
}).listen(30001);
}
执行该文件会看到有多个进程现在
2:创建httpClient.js用来请求刚才创建的30001端口的服务
var http = require("http");
var options = {
hostname: 'localhost',
port: 30001,
path: '/',
method: 'GET'
};
module.exports = function(callback){
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
callback(chunk.toString());
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
};
3:创建test.js测试同步跑多个请求,最后统计出各个进程走的请求数量
var async = require("async");
var httpClient = require("./httpClient");
var sum = 10;
var t = {"1":0, "2":0,"3":0, "4":0};
var c=0;
for(var i=0; i<sum; i++){
async.series([
function(cb){
httpClient(function(str){
if(str === "worker1")
t["1"] = parseInt(t["1"] || 0) + 1;
if(str === "worker2")
t["2"] = parseInt(t["2"] || 0) + 1;
if(str === "worker3")
t["3"] = parseInt(t["3"] || 0) + 1;
if(str === "worker4")
t["4"] = parseInt(t["4"] || 0) + 1;
cb();
});
}
], function(err, result){
if(err){
console.log(err);
}
c++;
if(c == sum){
console.log(t);
}
});
}
其中Express和cluster结合使用
创建clusterMaster.js
var http = require("http");
var cluster = require("cluster");
var numCPUs = require("os").cpus().length;
var workerList = [];
function createWorker(){
var worker = cluster.fork();
worker.on("message", function(data){
console.log("the worker " + worker.id + "|" + worker.process.pid + " accept data: " + JSON.stringify(data));
if(data.type && data.type === "broadcast"){
workerList.forEach(function(wk){
wk.send(data.body);
});
}
});
return worker;
};
if(cluster.isMaster){
console.log("master process start...");
for (var i = 0; i < numCPUs; i++) {
workerList.push(createWorker());
}
cluster.on('listening',function(worker, address){
console.log("A worker with #" + worker.id + " pid " + worker.process.pid +
" is now connected to " + address.address + ":" + address.port);
});
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
process.nextTick(function(){ cluster.fork(); });
});
}else{
require("./app.js");
}
以上cluster的功能就完成了,在app.js中添加监听message
process.on("message", function(data){
console.log("the process %s accept data: %s", process.pid, JSON.stringify(data));
});
在路由方法这种可以实现发送消息到master,master在.on("message")中收到消息后做操作
process.send({type: "broadcast", body:"ssssssss"});
以上就是node下cluster和express结合实现合理利用CPU
node cluster模块的使用和测试的更多相关文章
- node cluster模块,仿多线程并发调用,
worker.js var cluster = require('cluster')function fibo(n) { return n == 0 ? 0 : n > 1 ? fibo(n - ...
- Node.js的cluster模块——Web后端多进程服务
众所周知,Node.js是单线程的,一个单独的Node.js进程无法充分利用多核.Node.js从v0.6.0开始,新增cluster模块,让Node.js开发Web服务时,很方便的做到充分利用多核机 ...
- 【nodejs原理&源码赏析(4)】深度剖析cluster模块源码与node.js多进程(上)
[摘要] 集群管理模块cluster浅析 示例代码托管在:http://www.github.com/dashnowords/blogs 一. 概述 cluster模块是node.js中用于实现和管理 ...
- 【nodejs原理&源码赏析(4)】深度剖析cluster模块源码与node.js多进程(上)
目录 一. 概述 二. 线程与进程 三. cluster模块源码解析 3.1 起步 3.2 入口 3.3 主进程模块master.js 3.4 子进程模块child.js 四. 小结 示例代码托管在: ...
- 【nodejs原理&源码赏析(6)】深度剖析cluster模块源码与node.js多进程(下)
[摘要] cluster模块详解 示例代码托管在:http://www.github.com/dashnowords/blogs 阅读本章需要先阅读本系列前两章内容预热一下. 一. 引言 前两篇博文中 ...
- 【nodejs原理&源码赏析(6)】深度剖析cluster模块源码与node.js多进程(下)
目录 一. 引言 二.server.listen方法 三.cluster._getServer( )方法 四.跨进程通讯工具方法Utils 五.act:queryServer消息 六.轮询调度Roun ...
- Node.js模块
每一个Node.js都是一个Node.js模块,包括JavaScript文件(.js).JSON文本文件(.json)和二进制模块文件(.node). mymodul.js function Hell ...
- Node.cluster
nodejs是一个单进程单线程的引擎,只能利用到单个cpu进行计算,面对当今服务器性能的提高,cpu的利用率显然对node应有的性能大打折扣,面对这个问题,cluster应运而生. cluster介绍 ...
- Nodejs cluster模块深入探究
由表及里 HTTP服务器用于响应来自客户端的请求,当客户端请求数逐渐增大时服务端的处理机制有多种,如tomcat的多线程.nginx的事件循环等.而对于node而言,由于其也采用事件循环和异步I/O机 ...
随机推荐
- [转]mysqlx 同时使用 AND OR
- AngularJS form $addControl 注冊控件control
需求背景: 在form中使用编写的某component directive时.想通过form's name来对form中控件进行操作, 如使用$invalid等来ng-disabled btn. 解决 ...
- ajax 和jsonp 不是一码事 细读详解
由于Sencha Touch 2这种开发模式的特性,基本决定了它原生的数据交互行为几乎只能通过AJAX来实现. 当然了,通过调用强大的PhoneGap插件然后打包,你可以实现100%的Socket通讯 ...
- And Then There Was One(约瑟夫环)
https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_probl ...
- iOS与JS开发交互总结
hybrid.jpg 前言 Web 页面中的 JS 与 iOS Native 如何交互是每个 iOS 猿必须掌握的技能.而说到 Native 与 JS 交互,就不得不提一嘴 Hybrid. Hybri ...
- Linux安装virtualenvwrapper详细步骤
1.[root@localhost ~]# pip install virtualenvwrapper 2.[root@localhost ~]# pip list [root@localhost ~ ...
- Alex 的 Hadoop 菜鸟教程: 第2课 hadoop 安装教程 (CentOS6 CDH分支 yum方式)
原帖地址:http://blog.csdn.net/nsrainbow/article/details/36629339 我们这个教程是在 centos 上安装cdh的教程,并且使用的是yum方式. ...
- 创建第一个SpringBoot的demo程序
在这里,我只介绍手动创建的其中一种方式. 默认,你已经安装了IntelliJ IDEA和JDK1.8,如果没有,请先安装. 第一步:选择新建一个项目 File-->New-->Proj ...
- sql 2008数据事务日志已满处理方法
突然发现sql 2008出现错误:数据库 'mybase_db' 的事务日志已满.若要查明无法重用日志中的空间的原因,请参阅 sys.databases 中的 log_reuse_wait_desc ...
- did not find a matching property (tomcat+Eclipse 报错)
警告: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclips ...