如何设置RabbitMQ消费者的超时时间?

huangapple go评论81阅读模式
英文:

How to timeout rabbitmq consumer ?

问题

我有一个 RabbitMQ 消费队列的代码,但是一旦客户端订阅了队列,它就会一直消费队列。是否有一个超时机制,在队列为空后声明并退出?

msgs, err := ch.Consume(
    q.Name,   // 队列
    "",       // 消费者
    true,     // 自动确认
    false,    // 独占
    false,    // 不接收本地发布的消息
    false,    // 不等待
    nil,      // 参数
)
for msg := range msgs {
    log.Printf("接收到消息: %s", msg.Body)
}

以上是代码部分的翻译。

英文:

I have rabbitmq consuming the queue but once client is subscribed it stays consuming queue forever. Is there a timeout to declare and exit i.e. after queue is empty ?

 msgs, err := ch.Consume(
                q.Name, // queue
                "",     // consumer
                true,   // auto-ack
                false,  // exclusive
                false,  // no-local
                false,  // no-wait
                nil,    // args
        )
for msg := range msgs { 
                log.Printf("Received message with message: %s", msg.Body)
}

答案1

得分: 2

你可以使用标准的Go超时模式

这里是一个可工作的示例。

const duration = 3 * time.Second
timer := time.NewTimer(duration)
for {
    select {
    case d := <-msgs:
        timer.Reset(duration)
        fmt.Printf("Received a message: %s\n", d.Body)
    case <-timer.C:
        fmt.Println("Timeout!")
        os.Exit(1)
    }
}

这段代码可能需要一些改进,例如,当你接收到消息时停止计时器,并在处理完毕后再次启动计时器,但这应该能帮助你入门。

英文:

You can use the standard Go pattern for timing out.

Here is a working example.

const duration = 3 * time.Second
timer := time.NewTimer(duration)
for {
    select {
    case d := &lt;-msgs:
        timer.Reset(duration)
        fmt.Printf(&quot;Received a message: %s\n&quot;, d.Body)
    case &lt;- timer.C:
        fmt.Println(&quot;Timeout !&quot;)
        os.Exit(1)
    }
}

It probably needs some polishing, e.g. I suppose it would be better to stop the timer when you receive the message and enable it again when you are done processing it, but this should get you started.

huangapple
  • 本文由 发表于 2017年3月6日 21:23:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/42626817.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定