Using with Ruby

Using with Ruby (more generally)

The amqp gem is especially appropriate when running on a worker dyno, as it supports writing software that reacts to external events. For example, the following example will listen for messages on the amqpgem.examples.hello_world queue, and exit 60 seconds after it receives the first message.

require "rubygems"
require 'amqp'
require "amqp/extensions/rabbitmq"

EventMachine.run do
  connection = AMQP.connect(:host => '127.0.0.1', :port => 5672, :vhost => 'a')
  puts "Connecting to AMQP broker. Running #{AMQP::VERSION} version of the gem..."

  channel  = AMQP::Channel.new(connection)
  channel.queue("amqpgem.examples.hello_world", :auto_delete => true, :nowait => true) do |queue|
    exchange = channel.default_exchange

    queue.subscribe do |payload|
      puts "Received a message: #{payload}. Disconnecting..."

      EventMachine::Timer.new(60) do
        connection.close {
          EventMachine.stop { exit }
        }
      end
    end

    exchange.publish "Hello, world!", :routing_key => queue.name
  end
end