如何在使用PM2时配置主进程

the*_*lqd 5 ipc node.js pm2

我在NodeJS中遇到PM2问题.没有PM2,我们总是有一些代码行,如下所示配置主进程

if(cluster.isMaster){
    //master process configuration
} else {
    //worker process configuration
}
Run Code Online (Sandbox Code Playgroud)

确切地说,我想将消息从工作人员发送到主人,然后,主人将向所有工作人员发回消息以通知事件.

实际上,我看到,使用PM2时,主进程配置中没有代码行运行.

非常感谢您对此问题的任何想法!

joe*_*joe 7

如果您使用的 PM2 >2.5(即 2017 年 6 月之后),您可以使用NODE_APP_INSTANCE环境变量:

if(process.env.NODE_APP_INSTANCE === "0") {
  // the code in here will only be executed on the first instance in the cluster
}

// the code out here will be executed on all instances
Run Code Online (Sandbox Code Playgroud)

该变量仅在集群模式下可用。对于添加的每个新实例,它从零开始计数。我不确定为什么它是一个字符串而不是一个整数。


ste*_*kin 6

使用PM2,您通常不必使用此构造.通常,它看起来如下:

var cluster = require('cluster');  
var http    = require('http');  
var os      = require('os');
var numCPUs = os.cpus().length;

if(cluster.isMaster){
  for (var i = 0; i < numCPUs; ++i) {
    cluster.fork();
  }
} else {
  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end("hello world");
  }).listen(8080);
}
Run Code Online (Sandbox Code Playgroud)

对于PM2,上述的等价物是:

var http = require('http');

http.createServer(function(req, res) {  
  res.writeHead(200);
  res.end("hello world");
}).listen(8080);
Run Code Online (Sandbox Code Playgroud)

pm2 start app.js -i <number of instances>

你可以在这里阅读更多关于这个主题的内容

更新:您可以尝试通过传递命令行参数来区分主服务器和从服务器.这是一个示例ecosystem.json:

{
  "apps" : [
    {
      "name": "Master",
      "script": "app.js",
      "args": ["master"],
      "instances": "1",
    },
    {
      "name": "Slave",
      "script": "app.js",
      "args": ["slave"],
      "instances": "3"
    }
  ],
...
Run Code Online (Sandbox Code Playgroud)

然后,您可以执行以下操作:

argv = process.argv.slice(2) //stripe 'node', 'app.js' away

if (argv[0] === 'master'){
   // ...
} else {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

  • PM2 只是帮助自动分叉工人,但您不能实现类似:worker.on('message', messageHandler) 来处理从工人收到的消息:( (2认同)
  • 单独生成“master”可以吗?这很尴尬,但是在 Ecosystem.json 中为 master 添加一个单独的条目是可行的。PM2 允许为实例指定环境变量,这可以帮助您区分主从。 (2认同)