[英]node.js cluster: have each worker render different page
So I'm using cluster
to run some chat bots for some friends. 所以我正在使用cluster
为一些朋友运行一些聊天机器人。 And I use express
to run a single page for each bot. 我使用express
为每个bot运行一个页面。 However, cluster doesn't like that. 但是,集群不喜欢那样。 My code (abridged) is something akin to the following: 我的代码(节略)类似于以下内容:
var configs = {
bot1:"bot1",
bot2:"bot2"
};
if (cluster.isMaster) {
for (var bot in configs) {
cluster.fork( { file:configs[bot] } );
}
} else {
var file = process.env["file"];
var page = "/" + process.env["file"];
var express = require("express");
var web = express();
web.listen(3000);
web.get(page,function(req,res){
res.send( file );
});
}
And while this works good in theory, I'm only getting one bot with an output. 虽然从理论上讲这很好,但我只能得到一个带有输出的机器人。
If I go to example.com:3000/bot2
I get bot2
as an output. 如果我转到example.com:3000/bot2
bot2
得到bot2
作为输出。
If I go to example.com:3000/bot1
, I get Cannot GET /bot1
. 如果我转到example.com:3000/bot1
,则显示Cannot GET /bot1
。
It seems random which one will work, but never both of them. 哪一个会起作用似乎是随机的,但两者都不可行。
Apologies if it's something stupid simple, or if it can't be done. 抱歉,这很简单,还是无法完成。 I just find cluster
more effective at rebooting itself on exits and generally more stable than child_process
. 我只是发现cluster
在退出时重新启动自身更有效,并且通常比child_process
更稳定。 (sometimes, when I use child_process
, I'll end up with multiple instances of the same bot, which is tacky.) (有时,当我使用child_process
,我最终会child_process
同一机器人的多个实例,这很俗气。)
You seem to have misunderstood how cluster
works. 您似乎误解了cluster
工作原理。 It will not help for a situation like this and is primarily designed as a way to start multiple processes listening to the same port for HTTP connections. 它在这种情况下无济于事,并且主要设计为一种启动多个进程的方法,这些进程侦听HTTP连接的同一端口。
What you now have is: 您现在拥有的是:
/bot1
P2 =>监听端口3000处理/bot1
/bot2
P3 =>监听端口3000处理/bot2
When a request comes in on port 3000
, Node has no idea what the URL would be. 当请求通过端口3000
进入时,Node不知道URL是什么。 It just knows that both P2
and P3
are set up to handle requests on that port, so it will randomly choose one to handle the request. 它只是知道P2
和P3
都设置为处理该端口上的请求,因此它将随机选择一个来处理该请求。
If you send a request to /bot1 and Node randomly assigns it to be handled by P3
, then you will get the error you were seeing Cannot GET /bot1
, because P3
has no idea what that path means. 如果您将请求发送到/ bot1,并且Node随机将其分配给P3
处理,那么您将看到错误消息Cannot GET /bot1
,因为P3
不知道该路径意味着什么。 The same is true the other way around. 反之亦然。
Perhaps what you really want is some number of bot processes and a single process that listens on port 3000 and then forwards the messages to the bot processes using worker.send()
and such. 也许您真正想要的是一些bot进程和一个侦听端口3000的单个进程,然后使用worker.send()
等将消息转发到bot进程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.