2

我已经设置了 RabbitMQ,并且能够立即从 Rails 应用程序中发布和使用带有 bunny gem 的消息。在发布到 RabbitMQ 交换器时,我们如何以每条消息的预定义延迟时间实现延迟排队?

4

1 回答 1

4

使用 RabbitMQ 延迟消息交换插件: 有一个可用于延迟消息的插件,RabbitMQ 延迟消息交换插件。这个插件向 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

于 2017-02-01T10:32:32.210 回答