首页 > 解决方案 > 如何在一段时间没有消息后停止消费

问题描述

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

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

我阅读了有关Channel.cancel()的信息,但我只是不太确定在哪里将其插入到这里的流程中,因为该过程只是坐下来等待新消息,而且我不确定从哪里得到consumerTag它是不在msg变量中。

标签: javascriptnode.jsrabbitmqamqp

解决方案


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

推荐阅读