2017-02-01 46 views
1

我已經安裝了RabbitMQ並且能夠立即發佈和使用來自Rails應用程序的兔寶寶的消息。在發佈到RabbitMQ 交換時,我們如何以每條消息的預定義延遲時間實現延遲排隊?我們如何設置延遲排隊Bunny寶石和RabbitMQ?

+0

我很好奇。你爲什麼要延遲這個信息? – dnsh

+1

我在這裏執行一些背景工作。有些工作需要在特定的時間延遲後執行。 –

回答

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 

如下所述:https://www.cloudamqp.com/docs/delayed-messages.html