在 java RabbitMQ 客户端我可以做(ruby 代码):
consumer = QueueingConsumer.new(channel);
channel.basicConsume(queue_name, true, consumer);
consumer.nextDelivery.getBody
然后第三行阻塞线程直到消息到来。但是如何在Bunny客户端中实现呢? 我只能使用 block :
channel.queue('').bind(@x, :routing_key => rk).subscribe(block: true) do |_, _, payload|
# do something
end
或非阻塞弹出:
delivery_info, properties, payload = q.pop
有没有办法像在使用 Bunny 的 jruby 客户端中那样实现它?我想要的原因是在收到消息后我想在当前上下文中继续工作。
最佳答案
由于传递 :block => true
,对 subscribe
的调用被阻塞。如果您需要访问 block 外的有效负载,您可以利用 Ruby 的作用域规则:
the_payload = nil
queue = channel.queue('').bind(@x, :routing_key => rk)
queue.subscribe(block: true) do |delivery_info, _, payload|
the_payload = payload
channel.consumers[delivery_info.consumer_tag].cancel
end
# the_payload is now the one received in the block!
关于ruby - 如何使用 bunny RabbitMQ 客户端阻止订阅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16666288/