Nodejs學習之多進程架構

來源:互聯網
上載者:User

標籤:

作業系統的資源是有限的,這通常意味者作業系統分配給進程或線程的資源是有限的,在多核cpu普及的時代,如果只使用單核(常說node是單線程的),則無法充分壓榨硬體效能,今天和大家介紹的就是nodejs多進程架構,希望可以協助大家更好的學習nodejs ,一起來看看吧。 
模組介紹 
node提供了child_process模組,該模組提供4個方法 
1.spawn() 啟動一子進程來執行命令 
2.exec() 啟動一子進程來執行命令,與spawn()不同的是提供一個回呼函數獲知子進程的狀況 
3.execFile() 啟動一個子進程來執行可執行檔 
4.fork() 與spawn()類似,指定執行的javascript檔案模組即可 
慣用做法 
通常,node項目會有個bin目錄,裡面的檔案類似於應用程式入口,結合 commander 包實現根據命令列參數執行相應代碼邏輯的功能: 
var child_process = require(’child_process’); var fs = require(’fs’); var os = require(’os’); var program = require(’commander’); 
const EventEmitter = require(’events’).EventEmitter; const ee = new EventEmitter(); 
var config = require(’../config.json’); var DEFAULT_TRG_PATH = config.triggersPath; 
program.command(’start’) 
.description(’start the application’) 
.option(’-d, --directory,’, ’triggers path’, DEFAULT_TRG_PATH) 
.action(function(opts) { 
start(opts); 
}); 
program.command(’create’) 
.description(’start create’) 
.option(’-d, --directory,’, ’triggers path’, DEFAULT_TRG_PATH) 
.action(function(opts) { 
create(opts); 
}); 
program.parse(process.argv); 
function start(opts){ 
console.log(1111); 
}function create(opts){ 
console.log(1111); 
} 
假設需要執行 start 方式,僅需在命令列帶上 start參數即可: 
node ./bin/www start 
同理,其他方法可以通過該方式按需調用. 都不到為啥會扯到commander包的使用,可能是通常情況下想使用多進程架構時功能已經足夠複雜,而首先想到的就是用commander包使程式看上去比較好看吧-_- 
好了,言歸正傳,其實我就想使用線程池這種所謂的進階語言封裝好的方法而已,可惜node並沒有這種. 
很多文章都說過,API的用法,這裡只簡單說說他們之間的區別. 
spawn 
spawn會返回一個代後stdout與stderr流的對象,可以通過stdout流來讀取子進程返回給主進程的資料.如果子進程需要返回大量資料,則應該使用spawn而不是exec. 注意,stdout是以buffer格式返回,相對於exec而言,buffer資料可以很大,也就是說如果主進程需要接收子進程大量的資料時,應該選擇spawn來實現: 
var absScript = path.resolve(process.cwd()+’/lib/’, ’child.js’); var child = child_process.spawn(process.argv[0],[absScript,’create’,’--path=’ + dConfig.triggersPath + trgFile]); 
child.stdout.on(’data’, function(data){ 
console.log(`${data}`); 
}); 
child.stdout.on(’end’, function(){ 
console.log(’end’); 
}); 
child.on(’error’, function(err){ 
console.log(’Failed to start child process.’); 
}); 
child.on(’close’,function(code){ 
console.log(’closecode:’+ code); 
}); 
//child.jsconsole.log(’modelhunter.js’); var fs = require(’fs’); var program = require(’commander’); var trgs = require(’./components/trgs’); var ModelHunter = module.exports = {}; 
program.command(’create’) 
.description(’create’) 
.option(’-p, --path,’, ’triggers path’, ’’) 
.action(function(opts) { 
if(opts.path.length>0){ 
console.log(opts.path); 
setTimeout(function(){ 
console.log(’aaaaaaa’); 
process.exit(0); 
},1000); 
} 
}); 
program.parse(process.argv); 
最終輸出為 
modelhunter.js D:/xxxxx.xx 
aaaaaaa 
end closecode:0 
exec 與 execFile 
exec相當於spawn,通訊的內容有限制.適合執行複雜的shell命,與主進程的通訊是一次性的,子進程的結果只能返回一次. 
execFile跟exec類型,執行一個檔案,或指令碼或可執行檔等 
exec做了相當的封裝,主要用於執行複雜的shell命令. 
fork 
fork使用同樣的進程複製自身的環境執行指令碼,但只能執行node指令碼,fork可以很方便的與主進程進行通訊: 
//注意這裡第一個參數即是目標指令碼的路徑.var absScript = path.resolve(process.cwd()+’/lib/’, ’modelhunter.js’); var child = child_process.fork(absScript,[’create’,’--path=’ + dConfig.triggersPath + trgFile]); 
child.on(’message’,function(m){ 
console.log(’message:’+ m); //接收子進程訊息 
}); 
child.on(’close’,function(code){ 
console.log(code); 
}); 
child.send(’null’); //向子進程發送訊息 
//child.js 
process.on(’message’,function(m){ 
console.log(’chilid Listen:’, m); //接收主進程訊息 
}); 
process.send(’this childprocess’); //向主進程發送訊息 
總結 
如果想使用多進程架構,按需選擇相應的API.即可實作類別似"進程池"的功能,當然,可能要配合事件通知機制. 
這裡提出幾點疑問: 
1.如果是一個網站的服務端,為了充分利用CPU資源,通常會使用多進程架構,但是我們應該選擇fork還是spawn呢? 
2.pm2的fork mode 與 cluster mode有什麼區別? 

文章來源:繁星UED 

Nodejs學習之多進程架構

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.