Of Bunny and AMQP

talking about AMQP and the Bunny Ruby AMQP client

Archive for the ‘Howtos’ Category

Bunny Howto: Subscribe to a queue

leave a comment »

Bunny provides a simple way for a consumer to subscribe to queues. Here is an example -


require 'bunny'

my_client = Bunny.new
my_client.start
my_q = my_client.queue('my_queue')

ret = my_q.subscribe(:timeout => 5) { |msg| puts msg }
my_q.unsubscribe if ret == :timed_out

The Queue#subscribe method takes an optional timeout value and a mandatory code block.

The :timeout argument specifies how many seconds to wait for the next message to arrive on the queue before breaking out of the subscribe loop.

If a message arrives on the queue before the timeout period has elapsed, the message is processed and the timeout is reset to wait for the next message. If you do not provide a :timeout argument then a default timeout value of zero is used. This means that the subscribe will continue to process any received messages indefinitely until the process is halted by Ctrl-C for example.

The Queue#unsubscribe method cancels the consumer and tells the server to stop sending messages to that consumer. This does not affect messages that have already been delivered.

Both the Queue#subscribe and Queue#unsubscribe methods can take an optional :consumer_tag argument to identify the consumer. The server will generate a value for this if it is not passed explicitly.

The Queue#subscribe method also takes another two optional parameters -

  1. :ack => true or false – If set to true (default value is false), this argument tells the server that you will explicitly acknowledge receipt of messages (in Bunny this is done with the Queue#ack method).
  2. :header => true or false – If set to true (default value is false), when a message is received a hash containing :header, :payload and :delivery_details is passed to the code block. Otherwise, only the payload, which contains the message itself, is passed to the code block.

I am aware that there are problems with the timeout functionality in the Ruby 1.8.6 version of timeout.rb, however, I believe that most, if not all of these are solved in Ruby v1.9.1 and beyond. If the timeout option proves problematic for you under Ruby 1.8.6, let me know and I will explore alternative implementations.

To date I have not received any information one way or the other. Either people are using it and it has worked so far; people have had problems with it and have not told me about them; or no-one is using the Bunny subscribe functionality.

Above all, I hope that you enjoy using Bunny.

Written by Chris Duncan

August 20, 2009 at 8:52 pm

Posted in Bunny, Howtos

Tagged with , ,

Follow

Get every new post delivered to your Inbox.