【问题标题】:How to stop consuming after an amount of time of no messages如何在一段时间没有消息后停止消费
【发布时间】:2019-10-01 07:21:26
【问题描述】:

我正在尝试在队列未激活 5 分钟后关闭我的连接。我有:

  ch.consume(receivingQueue, async function (msg) {
    if (msg !== null) {
      console.log(msg.content.toString()));
    }
  });

我读到了Channel.cancel(),但我只是不太确定在哪里将其插入到这里的流程中,因为该过程只是坐着等待新消息,我不确定从哪里获得@987654323 @ 因为它不在 msg 变量中。

【问题讨论】:

  • 消费者标签是consume函数的返回值。您是否已调试/单步执行此代码?你在这里的第一行之后会发生什么?语句应该转到下一行。尝试将其设置为等于某个值(例如 let consumerTag = ch.consume(...
  • 另外,真正的问题是“你为什么要这样做?”

标签: javascript node.js rabbitmq amqp


【解决方案1】:

这个我没有测试过,但是逻辑如下。 setTimeout 设置为在每条消息 5 分钟后关闭连接。如果有新消息到达,则旧计时器会被新消息清除并重新创建新计时器。否则连接会在 5 分钟后关闭

 const closeConnection = function () {
       ch.close()
 }
 let timer = setTimeout(()=>{}, 0); //initial timer for cleartimeout Maybe refactor this?  

 ch.consume(receivingQueue, async function (msg) {
  clearTimeout(timer);
  timer = setTimeout(closeConnection, 300000)
  if (msg !== null) {
   console.log(msg.content.toString()));
  }
 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 2019-09-25
    • 2017-09-23
    • 2022-11-15
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多