ZeroMQ如何从消费者推向生产者

时间:2019-04-19 01:34:40

标签: node.js zeromq

我正在解决使用带有推/拉模式的ZeroMQ的练习,在此练习中,消费者应将结果通过另一条管道推向生产者。我有以下示例:

'use strict';
const cluster = require('cluster');
const fs = require('fs');
const zmq = require('zeromq');
const numWorkers = require('os').cpus().length;

if (cluster.isMaster) {
  // master's queue
  const pusher_m = zmq.socket('push').bind('ipc://filer-pp-m.ipc');
  // worker's queue
  const pusher_w = zmq.socket('push').bind('ipc://filer-pp-w.ipc');

  // Forward product to workers's queue
  for (let i = 0; i < 5; i++) {
    pusher_w.send(
      JSON.stringify({
        task: 'code'
      })
    );
  }

  // Event pull (master consumes master's queue)
  const puller_m = zmq.socket('pull').connect('ipc://filer-pp-m.ipc');
  puller_m.on('message', data => {
    const consumer = JSON.parse(data);
    console.log(`Worker's status: ${consumer.status}`);
  });

  // setup: initialize workers

  cluster.on('online',
    worker => console.log(`Worker ${worker.process.pid} is online.`));

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

} else {

  // Event pull (worker consumes worker's queue)
  const puller_w = zmq.socket('pull').connect('ipc://filer-pp-w.ipc');
  puller_w.on('message', data => {
    const consumer = JSON.parse(data);
    console.log(`Worker's task is ${consumer.task}`);
  });

  // Forward result to master's queue)
  const pusher_m = zmq.socket('push').connect('ipc://filer-pp-m.ipc');
  pusher_m.send(
    JSON.stringify({
      status: 'ready'
    })
  );
}

我仍然需要添加更多代码以使其按预期工作/正常运行。但是,现在,我正在尝试解决将结果从工作程序(子过程)推迟到生产程序(主过程)的问题,正如您在输出中看到的那样。

// output
/*
Worker 4341 is online.
Worker 4347 is online.
Worker 4346 is online.
Worker 4353 is online.
Worker's task is code
Worker's task is code
Worker's task is code
Worker's task is code
Worker's task is code
*/

出于测试目的,我试图将工人的套接字绑定到工人的条件块(例如,其他)中,看来生产者(主机)能够从主机的队列中提取一条消息。但我认为这是不对的,因为掌握绑定套接字的主机似乎是稳定的过程。

有人可以帮助我吗?如有疑问,请提出评论。

0 个答案:

没有答案