您好,登錄后才能下訂單哦!
本文主要給大家介紹了關于node.js中cluster使用的相關教程,分享出來供大家參考學習,下面來看看詳細的介紹:
一、使用NODE中cluster利用多核CPU
var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // 創建工作進程 for (var i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('death', function(worker) { console.log('worker ' + worker.pid + ' died'); cluster.fork();//重啟子進程 }); } else { // 工作進程創建http 服務器 http.Server(function(req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(8000); }
二、通過消息傳遞來監控工作進程狀態
var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus().length; var rssWarn = (12 * 1024 * 1024) , heapWarn = (10 * 1024 * 1024) if(cluster.isMaster) { for(var i=0; i<numCPUs; i++) { var worker = cluster.fork(); worker.on('message', function(m) { if (m.memory) { console.log(m.memory.rss,rssWarn) if(m.memory.rss > rssWarn) { console.log('Worker ' + m.process + ' using too much memory.') } } }) } } else { // 服務器 http.createServer(function(req,res) { res.writeHead(200); res.end('hello world\n') }).listen(8000) // 每秒報告一次狀態 setInterval(function report(){ process.send({memory: process.memoryUsage(), process: process.pid}); }, 1000) }
三、殺死僵尸進程
var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus().length; var rssWarn = (50 * 1024 * 1024) , heapWarn = (50 * 1024 * 1024) var workers = {} if(cluster.isMaster) { for(var i=0; i<numCPUs; i++) { createWorker() } setInterval(function() { var time = new Date().getTime() for(pid in workers) { if(workers.hasOwnProperty(pid) && workers[pid].lastCb + 5000 < time) { console.log('Long running worker ' + pid + ' killed') workers[pid].worker.kill() delete workers[pid] createWorker() } } }, 1000) } else { // 服務器 http.Server(function(req,res) { // 打亂200 個請求中的1 個 if (Math.floor(Math.random() * 200) === 4) { console.log('Stopped ' + process.pid + ' from ever finishing') while(true) { continue } } res.writeHead(200); res.end('hello world from ' + process.pid + '\n') }).listen(8000) // 每秒鐘報告一次狀態 setInterval(function report(){ process.send({cmd: "reportMem", memory: process.memoryUsage(), process: process.pid}) }, 1000) } function createWorker() { var worker = cluster.fork() console.log('Created worker: ' + worker.pid) // 允許開機時間 workers[worker.pid] = {worker:worker, lastCb: new Date().getTime()-1000} worker.on('message', function(m) { if(m.cmd === "reportMem") { workers[m.process].lastCb = new Date().getTime() if(m.memory.rss > rssWarn) { console.log('Worker ' + m.process + ' using too much memory.') } } }) }
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。