如何使用 Node.js 集群将消息(对象)从 worker 发送到 Master(主)

How to send a message (object) from workers to Master (primary) with Node.js Cluster

看来我从工人那里发来的信息不是我从主人那里收到的信息。我应该收到 {test: true} 并且我收到了这个具有所有这些属性的长对象。

当我更改事件侦听器的位置并将其放入 worker 创建循环时,可能会有所帮助 (for (let i = 0; i < 2; i++) {let worker = cluster.fork()}),我收到了正确的 ({test: true}).

我错过了什么?

这是代码:

if (cluster.isMaster) {
            console.log(`Master ${process.pid} is running`)

            cluster.on('message', (msg) => {
                    if (msg.test) {
                        console.log('✅')
                    } else {
                        console.log('Message received without the content "test : true"')
                    }
                    console.log('--------- msg : , 'msg)

                })

            for (let i = 0; i < 2; i++) {
                let worker = cluster.fork()
            }

        } else {
            setTimeout(() => {
                process.send({test: true})
            }, 1000)

        }

这是终端输出:

Master 84458 is running
Message received without the content "test : true"
Message received without the content "test : true"


--------- msg : {
  _events: [Object: null prototype] { message: [Function (anonymous)] },
  _eventsCount: 1,
  _maxListeners: undefined,
  exitedAfterDisconnect: undefined,
  state: 'online',
  id: 2,
  process: <ref *1> ChildProcess {
    _events: [Object: null prototype] {
      internalMessage: [Array],
      error: [Function (anonymous)],
      message: [Function (anonymous)],
      exit: [Function],
      disconnect: [Function]
    },
    _eventsCount: 5,
    _maxListeners: undefined,
    _closesNeeded: 2,
    _closesGot: 0,
    connected: true,
    signalCode: null,
    exitCode: null,
    killed: false,
    spawnfile: '/usr/local/bin/node',
    _handle: Process {
      onexit: [Function (anonymous)],
      pid: 83453,
      [Symbol(owner_symbol)]: [Circular *1]
    },
    spawnargs: [
      '/usr/local/bin/node',
      '/home/stef/Dev/apps/Trading-Center/index.js'
    ],
    pid: 83453,
    stdin: null,
    stdout: null,
    stderr: null,
    stdio: [ null, null, null, null ],
    channel: Control {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    },
    _handleQueue: null,
    _pendingMessage: null,
    send: [Function (anonymous)],
    _send: [Function (anonymous)],
    disconnect: [Function (anonymous)],
    _disconnect: [Function (anonymous)],
    [Symbol(kCapture)]: false,
    [Symbol(kChannelHandle)]: Pipe {
      pendingHandle: null,
      sockets: [Object],
      buffering: false,
      [Symbol(kJSONBuffer)]: '',
      [Symbol(kStringDecoder)]: [StringDecoder]
    }
  },
  [Symbol(kCapture)]: false
}

你的问题出在message监听回调,第一个参数是worker对象,第二个是消息对象。您发布的日志,就是工作人员本身。

更改自:

cluster.on('message', (msg)

收件人:

cluster.on('message', (worker, msg)

PS:我提供了一个示例演示 here,打开终端并输入 node app.js 到 运行 应用程序。