一段时间没有消息后如何停止消费

时间:2019-10-01 07:21:26

标签: javascript node.js rabbitmq amqp

队列5分钟未处于活动状态后,我试图关闭我的连接。我有:

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

我读到了Channel.cancel()的内容,但是我不确定在哪里将其插入流程中,因为流程只是在等待新消息,所以我不确定在哪里获取。 consumerTag,因为它不在msg变量中。

1 个答案:

答案 0 :(得分:0)

我还没有测试过,但是逻辑如下。 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()));
  }
 });