master.js
const cp = require('child_process');
const fork = cp.fork;
const os = require('os');
const cpus = os.cpus();
const Net = require('net');
const muti_process = [];
const port = 1337;
const host = '127.0.0.1';
const server = new Net.Server();
for(let i = 0, length = cpus.length; i < length; i ++) {
muti_process.push(fork('./server.js'));
}
server.listen(port, host, () => {
muti_process.forEach((process) => {
process.send('server', server);
});
server.close();
console.log(`server listen on port ${port}`);
});
server.js
const Net = require('net');
const port = process.port || 8080;
const host = '127.0.0.1';
const server = new Net.Server();
function sleep (second) {
second = parseInt(second, 10);
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, second * 1000);
});
}
let allSpend = 0;
server.on('connection', (socket) => {
console.log('a new connection has been established.');
const start = Date.now();
console.log('start time:', start);
socket.on('data', (chunk) => {
console.log(`received data from client...`);
response(chunk);
});
socket.on('end', () => {
console.log('Closing connection with the client.\n');
});
async function response (chunk) {
console.log(`wait for ${ allSpend } s....`);
await sleep(3);
socket.write(chunk.toString());
socket.end();
console.log(`request spend ${Math.floor( ( Date.now() - start ) / 1000 ) } s`);
allSpend += 3;
}
});
server.on('error', (err) => {
console.log(err);
});
// server.listen(port, host, () => {
// console.log(`server is runing on port ${port}\n`);
// });
process.on('message', (message, tcp) => {
if(message == 'server') {
tcp.on('connection', (socket) => {
console.log(`handled by process ${process.pid}`);
server.emit('connection', socket);
});
}
});
master 启动多进程 node 服务, 本意是当请求 localshot:1337/ 的时候, 将单进程时的服务器处理两个请求需要的 6 秒减少为多进程下的 3 秒, 但是目前在多进程下依然是 6 秒,请问各位 child_process 模块能否提高请求响应速度? 如果能应该怎么做? 如果不能, child_process 的本意是什么? 恳求回答 附上项目代码: https://github.com/zhangxiang958/ComputerNetworkLab/blob/master/Socket1_WebServer/source/muti_process/server.js
可以使用pm2来进行负载均衡
@fruit-memory 是的, 但是 pm2 还是使用了 cluster 模块, 我想知道有没有用 child_process 做到均衡的效果的可能, 目前我的代码并没有做到
少年,cluster
底层就是 child_process
,你是想自己实现一套 cluster 么
https://github.com/nodejs/node/blob/master/lib/internal/cluster/master.js
child_process
的本意就是开一个新的进程。
@atian25 好的, 明白, 谢谢天猪大大, 问题清楚了, 是我负载均衡没有做好
@zhangxiang958 老实说,用这个做负载没啥意义,只是单机的而已。
@atian25 是的是的, 这个只是我用来做计算机网络 lab 的个人学习代码, 想由此进一步学习一下 cluster 的底层.