我已经设置了RabbitMQ并且能够立即从rails应用程序发布和使用带有bunny gem的消息。在发布到RabbitMQ时,我们如何通过每个消息的预定延迟时间实现延迟排队 交换?
答案 0 :(得分:3)
使用RabbitMQ延迟消息交换插件 有一个插件可用于延迟消息,RabbitMQ delayed messages exchange plugin。此插件向RabbitMQ添加新的交换类型,并且路由到该交换的消息可以延迟指定的时间量。
合并TTL和DLX以延迟邮件传递 另一种选择是结合TTL和DLX来延迟消息传递。通过将这些组合到函数中,我们将消息发布到队列,该队列将在TTL之后使其消息到期,然后将其重新路由到交换机并使用死信路由密钥,以便它们最终进入我们消耗的队列。
require 'bunny'
B = Bunny.new ENV['CONNECTION_URL']
B.start
DELAYED_QUEUE='work.later'
DESTINATION_QUEUE='work.now'
def publish
ch = B.create_channel
# declare a queue with the DELAYED_QUEUE name
ch.queue(DELAYED_QUEUE, arguments: {
# set the dead-letter exchange to the default queue
'x-dead-letter-exchange' => '',
# when the message expires, set change the routing key into the destination queue name
'x-dead-letter-routing-key' => DESTINATION_QUEUE,
# the time in milliseconds to keep the message in the queue
'x-message-ttl' => 3000
})
# publish to the default exchange with the the delayed queue name as routing key,
# so that the message ends up in the newly declared delayed queue
ch.default_exchange.publish 'message content', routing_key: DELAYED_QUEUE
puts "#{Time.now}: Published the message"
ch.close
end
def subscribe
ch = B.create_channel
# declare the destination queue
q = ch.queue DESTINATION_QUEUE, durable: true
q.subscribe do |delivery, headers, body|
puts "#{Time.now}: Got the message"
end
end
subscribe()
publish()
sleep