Example #1
0
  channelManager.findOrCreateProducer = function (topic, options, unusedChannelTimeoutMs) {
    let channel = producersByTopic[topic];
    if (channel) return channel;
    options = options ? options : {};

    channel = producersByTopic[topic] = channelManager.createRawProducer(topic, options);

    let unusedChannelTimeout;

    channelManager.emit(channelManager.PRODUCER_NEW_TOPIC_EVENT, topic);

    channel.publish_ = channel.publish;
    channel.publish = function (message, cb) {
      clearTimeout(unusedChannelTimeout);

      if (unusedChannelTimeoutMs) {
        unusedChannelTimeout = setTimeout(onUnusedChannelTimeout, unusedChannelTimeoutMs);
      }

      channel.publish_(message, function (err) {
        if (err) return cb(err);
        channelManager.emit(channelManager.PRODUCER_NEW_MESSAGE_EVENT, topic);
        cb();
      });
    };

    function onUnusedChannelTimeout() {
      removeProducer(channel, topic);
    }

    return channel;
  };