我已经安装了RabbitMQ,能够立即发布和使用来自rails应用程序的兔子创业板消息。在发布到RabbitMQ交换时,如何实现每条消息预定义延迟时间的延迟排队?
发布于 2017-02-01 10:32:32
使用RabbitMQ延迟消息交换插件:有一个可用于延迟消息的插件,RabbitMQ延迟消息交换插件。这个插件向RabbitMQ添加了一个新的交换类型,并且路由到该交换的消息可以延迟指定的时间。
结合TTL和DLX来延迟消息传递:另一种选择是将TTL和DLX组合起来以延迟消息传递。通过将这些信息组合到函数中,我们将消息发布到一个队列中,该队列将在TTL之后终止其消息,然后将其重新路由到exchange,并使用死信路由密钥,从而使它们最终进入我们使用的队列中。
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
https://stackoverflow.com/questions/41976840
复制相似问题