本文主要
介绍了集群在Node.js使用的相关
教程,
分享出来供大家
参考。下面是下面的
详细介绍:
1。在节点中使用多核CPU
VaR集群=需要('cluster);
var http =需要('http');
无功numcpus =需要('os)。CPU(长度);
如果(集群。是大师){
创建工作流程
对于(var i = 0;i < numcpus;i++){
Cluster.fork();
}
Cluster.on(死亡,
功能(工人){
console.log('worker + worker.pid +‘死');
(集群.叉);重新
启动过程
});
{人}
创建HTTP
服务器
进程 HTTP服务器(功能(REQ,RES){
(200)res.writehead;
res.end(你好世界;
}听(8000);
}
两。通过
消息传递监视工作过程的状态
VaR集群=需要('cluster);
var http =需要('http');
无功numcpus =需要('os)。CPU(长度);
无功rsswarn =(12×1024×1024)
heapwarn =(10×1024×1024)
如果(集群。是大师){
对于(var i = 0;i < numcpus;i++){
VaR的工人= cluster.fork();
worker.on(消息功能(M){
如果(m.memory){
console.log(m.memory.rss,rsswarn)
如果(m.memory.rss > rsswarn){
console.log('worker +过程+ M.使用太多
内存。)
}
}
})
}
{人}
服务器
http.createserver(功能(REQ,RES){
(200)res.writehead;
res.end(你好世界')
}听(8000)
第二个
报告状态
setInterval(功能报告(){)
process.send({内存:process.memoryusage(),过程:过程。PID });
},1000)
}
三。杀死僵尸进程
VaR集群=需要('cluster);
var http =需要('http');
无功numcpus =需要('os)。CPU(长度);
无功rsswarn =(50×1024×1024)
heapwarn =(50×1024×1024)
var工作者= { }
如果(集群。是大师){
对于(var i = 0;i < numcpus;i++){
CreateWorker()
}
setInterval(){()
函数(
VAR时间=新的
日期()GetTime()。
对于(工人中的PID){
如果(workers.hasownproperty(PID))
工人{ PID }。lastcb+5000<时间){
console.log(职工+
运行PID +杀)
工人worker.kill(){ PID }。
删除工人{ } }
CreateWorker()
}
}
},1000)
{人}
服务器
HTTP服务器(功能(REQ,RES){
200 在请求1中打乱
如果(Math.floor(数学。随机)(* 200)= = = 4){
console.log('stopped + process.pid +从整理的)
当(true){继续}
}
(200)res.writehead;
res.end('Hello World'+ process.pid + ')
}听(8000)
状态报告每秒
setInterval(功能报告(){)
process.send({
命令:reportmem
过程:过程。
},1000)
}
功能createworker(){
VaR的工人= cluster.fork()
console.log('created工人:+工人。PID)
允许/引导时间
工人{ } = {工人。PID工人:工人,lastcb:新的日期()GetTime()GetTime()1000 }。
worker.on(消息功能(M){
如果(m.cmd = reportmem){
工人m.process } {。lastcb =新的日期()GetTime()。
如果(m.memory.rss > rsswarn){
console.log('worker +过程+ M.使用太多内存。)
}
}
})
}
总结
以上就是本文的全部内容。希望本文的内容能给大家的
学习或工作带来一定的帮助。如果有任何疑问,您可以留言交流,谢谢您的
支持。