简体   繁体   中英

node.js cluster: have each worker render different page

So I'm using cluster to run some chat bots for some friends. And I use express to run a single page for each 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.

If I go to example.com:3000/bot1 , I get 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 . (sometimes, when I use child_process , I'll end up with multiple instances of the same bot, which is tacky.)

You seem to have misunderstood how cluster works. 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.

What you now have is:

  • P1 => Master process which starts P2 and P3.
  • P2 => Listening on port 3000 handling /bot1
  • P3 => Listening on port 3000 handling /bot2

When a request comes in on port 3000 , Node has no idea what the URL would be. 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM