node多进程服务器

node提供了四种方法来建立子进程,分别是child_process.exec(),child_process.execFile(),
child_process.fork(),child_process.spawn()。他们都返回子进程对象。
exec:启动一个子进程执行命令,而且有一个回调函数获知子进程的情况。而且能够设置超时时间。
execFile:启动一个子进程文件,注意这里的文件不必定是js文件,node能够执行的文件,例如window下的
bat文件,等而且也有一个回调,而且能够设置超时时间。
spawn:只是简单的执行一个子进程命令。不能设置超时时间。
fork:执行一个文件,不能设置超时和回调。node


node进程间通讯,指父进程和子进程之间的通讯,子进程之间是不能够通讯的,有点想react的组件。经过send和message事件进行通讯。react

//parent.js服务器

let cp = require('child_process');
let n = cp.fork('./p_sub.js');
let time = new Date();
console.log('current time:'+ time);
n.on('message',function(msg){
console.log(`time have passd ${new Date() - time}`);
console.log('parent get message:' + msg.foo);
})
n.send({hello:'world'});
console.log('send ok');
while((new Date()) - time < 20){
// do nothing...
}负载均衡

 

//sbu.js异步

let time = new Date();
console.log('current time:'+ time);
process.on('message',function(m){
console.log('massage from parent:' + m.hello);
process.send({foo:'bar'});
})socket

父子进程间通讯如此简单。接下来就要谈论关键的东西了,node的多进程服务器。在这以前,咱们还须要了解的一个东西叫作句柄,句柄能够理解问表示资源的引用,总感受像是指针这样的东西,能够理解为js对象名和对象之间的关系,不过这是系统对资源的引用,句柄能够是一个socket对象,套接字,管道等。父进程和子进程之间能够传递句柄。这就是弄的多进程服务器的关键,主进程接受80端口(固然也能够其余端口)请求,而后将句柄 传递个子进程,由子进程处理,而后将结果发送给主进程。岂不是很好。异步I/O单线程,又充分利用cpu资源。若是这样理解那你就错了。其实node发送的句柄,并非真正的对象,而是这个对象的引用,这是一个抢占是服务至关于多个进程同时监听了同一个端口。tcp

//process.js函数

let sub_process = require('child_process');
let child1 = sub_process.fork('./p_children.js');
let child2 = sub_process.fork('./p_children.js');
let child3 = sub_process.fork('./p_children.js');ui

let server = require('net').createServer();
server.listen(1337,function(){
child1.send('server',server);
child2.send('server',server);
child3.send('server',server);
server.close();
})spa

 

//p_children.js

let http = require('http');
let server = http.createServer(function(req,res){
res.writeHead(200,{'Conten-Type':'text-plain'});
res.end('handle by child,pis is ' + process.pid);
});

process.on('message',(m,tcp)=>{
if(m==='server'){
tcp.on('connection',function(socket){
server.emit('connection',socket);
})
}
})

这只是万里长征的第一步,单线程总归是不稳定的,例如检测到子进程推出后重启另外一个进程,而且限制子进程数量,子进程之间要作负载均衡,又忽然感受一脸蒙蔽,为应对这些node引入了cluster模块,解决多cpu利用率问题,上面提到的这些问题用cluster模块轻松搞定。

var cluster = require('cluster');

cluster.setupMaster({

exec:'p_children.js'

})

let cpus = require('os').cpus();

for(let i=0;i<cpus.length;i++){

cluster.fork();

}

这样以来就感受爽歪歪了,不过淡定,如今用pm2直接配置就能够作这个事情,因此上面你看的没用,直接用pm2就对了。因此上面说的基本是扯淡。

相关文章
相关标签/搜索