关于以下代码,应用程序应在每个连接上分叉4个worker,然后每个worker发送一条消息并断开连接。
但是,在第一次连接后,<lvc:CartesianChart Hoverable="False" DataTooltip="{x:Null}" />
会逐渐收到消息。
cluster.on('message')
首先输出:
const express = require('express');
const cluster = require('cluster');
if (cluster.isMaster) {
const app = express();
app.get('/', (req, res) => {
[1, 2, 3, 4].map(() => cluster.fork());
const count = [];
cluster.on('message', (worker, message) => {
console.log({
worker: worker.id,
message
});
count.push(true);
if (count.length === 4)
return res.sendStatus(200);
});
});
app.listen(8000, () => console.log('listening on 8000'));
} else if (cluster.isWorker) {
process.send('msg');
process.disconnect();
}
然后
> curl localhost:8000
> { worker: 4, message: 'msg' }
> { worker: 1, message: 'msg' }
> { worker: 2, message: 'msg' }
> { worker: 3, message: 'msg' }
依旧......
我无法理解为什么会这样。
答案 0 :(得分:3)
您的问题源于您使用.on(“message”,...)的方式。实际上,每次调用服务器时都会注册监听器。
将侦听器中的“push to count”部分移出API调用可以解决此问题:
if (cluster.isMaster) {
let count = [];
cluster.on('message', (worker, message) => {
console.log({
worker: worker.id,
message
});
count.push(true);
});
const app = express();
app.get('/', (req, res) => {
[1, 2, 3, 4].forEach(() => cluster.fork());
let msgHandler = (worker, message) => {
if (count.length === 4) {
cluster.removeListener('message', msgHandler); // Do not forget to remove this event listener, or the issue will arise again!
count.length = 0;
return res.sendStatus(200);
}
};
cluster.on('message', msgHandler);
});
app.listen(10101, () => console.log('listening on 10101'));
} else if (cluster.isWorker) {
process.send('msg');
process.disconnect();
}