我使用bunny ruby gem向rabbitmq服务器发送和接收消息如何在设置等待时间超时(即,如果3秒后没有消息到达,则停止阻止)的同时同步从队列中弹出消息?
一个明显的解决方案是循环POP调用,直到超时或收到消息为止,但这似乎非常低效。有更优雅的解决方案吗我查看了bunny的文档以及rabbitmq站点上的教程,但是我没有找到这个特定场景的解决方案。
最佳答案
为了使这样的特性a被迫重写基本方法subscribe。我发现我们可以为一个通道设置超时时间,但是函数中没有这样的输入参数。
response = nil
subscribe(block: true, timeout: 10) do |delivery_info, properties, payload|
Rails.logger.info "got message #{payload}"
response = payload
@channel.consumers[delivery_info.consumer_tag].cancel
end
def subscribe(opts = {block: false}, &block)
ctag = opts.fetch(:consumer_tag, @channel.generate_consumer_tag)
consumer = Bunny::Consumer.new(@channel,@response_queue,ctag)
consumer.on_delivery(&block)
@channel.basic_consume_with(consumer)
if opts[:block]
@channel.work_pool.join(opts[:timeout])
end
end