[英]How to send a message (object) from workers to Master (primary) with Node.js Cluster
我从工人那里发送的消息似乎不是我从主那里收到的消息。 我应该收到 {test: true} 并且我收到这个具有所有这些属性的长对象。
也许知道当我更改事件侦听器的位置并将其放入工作线程创建循环时会有所帮助(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:我在这里放了一个示例演示,打开终端并输入node app.js
来运行应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.