我有一个集群节点应用程序,我正在寻找一种方法来从一个请求中获取所有工作人员的状态。
我用快递问masten,但它与快递无关。有一个请求,我想要这样的东西:
[
{
pid: 'xxxxxx',
state: 'I\'m fine'
},
{
pid: 'xxxxxx',
state: 'I\'m sick'
},
{
pid: 'xxxxxx',
state: 'I\'m fine'
},
]
要发送明确的答案,我需要等待所有工作人员的答案,然后将它们连接起来。但问题是:如何等待工人而不是简单的听众的具体回答?
这是集群应用程序的代码示例。我正在尝试在http://localhost:8000/的请求中获取先前的 Json
import * as cluster from 'cluster';
import * as express from 'express';
if (cluster.isMaster) {
// Here is master
// we start by creating few workers
for (let i = 0; i < 4; i++) {
cluster.fork();
}
// for each worker, if we receive a message, we print it
for (const id in cluster.workers) {
if (cluster.workers.hasOwnProperty(id)) {
cluster.workers[id].on('message', (msg) => {
console.log(`[${cluster.workers[id].process.pid}] ${msg}`);
});
}
}
// create express server
const app = express();
app.get('/', (req, res) => {
// request from client
console.log('\nHow are you all?');
// for each workers
for (const id in cluster.workers) {
if (cluster.workers.hasOwnProperty(id)) {
// ask state
cluster.workers[id].send('howareyou');
// how to wait for answer?
}
}
// probably concat all answers here
// send result to client
res.setHeader('Content-Type', 'application/json');
res.json({question: 'How can I have state of all my workers?'});
});
app.listen(8000);
} else {
// Here is worker.
process.on('message', (message) => {
// When master ask state, send back random answer
if (message === 'howareyou') {
process.send(`I'm ${Math.random() * 100 < 75 ? 'fine' : 'sick'}`);
}
});
}
提前致谢 :)