CloudAMQP with Ruby Getting started

Client libraries Many options

Ruby developers has a number of options for AMQP client libraries:

  • AMQP "the" AMQP client, evented, super fast and super well maintained
  • Bunny is the most popular synchronous client
  • Hot Bunnies is an idiomatic, fast and well-maintained (J)Ruby DSL on top of the RabbitMQ Java client

Code example Publish and subscribe synchronously

The following example will use the synchronous client Bunny and publish a message and then consume it.

require "bunny" # don't forget to put gem "bunny" in your Gemfile

b = Bunny.new ENV['CLOUDAMQP_URL']
b.start # start a communication session with the amqp server

q = b.queue("test1") # declare a queue

# declare default direct exchange which is bound to all queues
e = b.exchange("")

# publish a message to the exchange which then gets routed to the queue
e.publish("Hello, everybody!", :key => 'test1')

msg = q.pop[:payload] # get message from the queue

puts "This is the message: " + msg + "\n\n"

b.stop # close the connection

Code example using Sneakers

The following example will use sneakers to consume a message from RabbitMQ

#sneakers_app.rb

require 'sneakers' # don't forget to put gem "sneakers" in your Gemfile
require 'sneakers/runner'

Class Processor
  include Sneakers::Worker
  from_queue :default_queue
  def work(msg)
    puts "Msg received: " + msg
  end
end

opts = {
  :amqp => 'CLOUDAMQP_URL',
  :vhost => 'username',
  :exchange => 'sneakers',
  :exchange_type => :direct
}

Sneakers.configure(opts)
r = Sneakers::Runner.new([Processor])
r.run

Run your application, $ ruby sneakers_app.rb .

If you go to your RabbitMQ admin console -> queues, you will see that a new queue named default_queue is created. Push a couple of messages by entering a text into the payload under Publish message, and press Publish message. You should now see some output in your terminal, telling you that the message is received and that it is ready to be handled.

Code example Build realtime apps!

Here's another example which uses the evented AMQP library, in combination with Sinatra and Server Sent Events. It shows how to build a simple real time application, using CloudAMQP as the backbone.

The application can also be seen live at amqp-sse.herokuapp.com.

Video

Here's a video recording showing how to setup a CloudAMQP instance and connect to it using Ruby and the Bunny library:

Further reading