Nodejs 求指导:根据url路由到不同的子进程进行处理
Nodejs 求指导:根据url路由到不同的子进程进行处理
我希望能用一个master生成若干childprocess,由master负责接收request,然后根据url路由到不同的childprocess进行处理(这是由于数据同步要求只能分派到固定的一个process进行处理),这显然无法用cluster解决。当然也可以让子进程侦听不同端口,由master转发request,但这样要引入额外间接层和开销。 是否有高手可以提供指导,不胜感激!
2 回复
好的,下面是一个简化的示例来实现你的需求,即使用Node.js中的child_process
模块来创建子进程,并根据URL路由到不同的子进程进行处理。
示例代码
const http = require('http');
const { fork } = require('child_process');
// 创建子进程
const child1 = fork('./child1.js');
const child2 = fork('./child2.js');
const server = http.createServer((req, res) => {
const url = req.url;
// 根据URL选择子进程
if (url.startsWith('/path1')) {
child1.send({ type: 'HANDLE_REQUEST', data: { req, res } });
} else if (url.startsWith('/path2')) {
child2.send({ type: 'HANDLE_REQUEST', data: { req, res } });
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
子进程代码(child1.js)
process.on('message', message => {
if (message.type === 'HANDLE_REQUEST') {
const { req, res } = message.data;
// 处理请求并响应
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Path 1 Response');
}
});
子进程代码(child2.js)
process.on('message', message => {
if (message.type === 'HANDLE_REQUEST') {
const { req, res } = message.data;
// 处理请求并响应
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Path 2 Response');
}
});
解释
-
主进程:
- 使用
fork
方法创建两个子进程child1
和child2
。 - 创建HTTP服务器,监听客户端的请求。
- 根据请求的URL将请求发送给对应的子进程。
- 使用
-
子进程:
- 监听来自主进程的消息,当收到消息时,处理请求并返回响应。
通过这种方式,你可以根据URL将请求路由到不同的子进程进行处理,而不需要为每个子进程分配不同的端口。这种方式减少了额外的间接层和开销。