June 19, 2010

Simple RabbitMQ Subscriber Using Bunny


This is a very simple example of an RabbitMQ subscriber in Ruby using the bunny gem. It uses the dead_letter pattern to resend failures to another queue if processing fails. The original message is ack'd so it does not get reprocessed. Something else probably needs to be monitoring the messages on the dead_letter queue.

Signal.trap('INT') { @subscriber.shutdown }
Signal.trap('TERM') { @subscriber.shutdown }

class Subscriber
  def initialize
    @bunny = Bunny.new(...)
    @queue = ...
    @dead_letter = ...
  end
  
  def run
    @queue.subscribe(:ack => true) do |msg|
      payload = JSON.parse(msg[:payload])
      begin
        do_something_with_the_payload(payload)
      rescue StandardError, Timeout::Error => error
        routing_key = msg[:delivery_details][:routing_key]
        @dead_letter.publish(payload, :key => routing_key)
      end
    end
  end

  def shutdown
    @queue.unsubscribe rescue nil
    @bunny.stop rescue nil
    exit
  end
end

@subscriber = Subscriber.new
@subscriber.run
 

This is the personal blog of Simon Horne. I currently work as a Software Developer for Streetline Networks in San Francisco.




Copyright © 2010 Simon Horne

About This Website

This website is primarily a demonstration of various tools, technologies and techniques used in the construction of a simple website.

Contact Details