node多进程服务器

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


node进程间通信,指父进程和子进程之间的通信,子进程之间是不可以通信的,有点想react的组件。通过send和message事件进行通信。

//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'});
})

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

//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');

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

//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就对了。所以上面说的基本是扯淡。

猜你喜欢

转载自www.cnblogs.com/node-jili/p/10169398.html