How to run RabbitMQ with Ruby

RabbitMQ acts as a message broker, standing between two different applications and passing messages on for processing. In doing so, RabbitMQ needs to be able to speak different languages, which is accomplished through the use of client libraries, which are plentiful and in use worldwide by many developers. In this tutorial, we discuss the use of RabbitMQ in Ruby with the Bunny, Sneakers, and March Hare libraries. For your convenience, all code has been made available on Github.

This article assumes that you have a running RabbitMQ server, so if not, you are welcome to get started with a free RabbitMQ plan at CloudAMQP. CloudAMQP.

The article cover:

  • Installing Bunny with Rubygems
  • Installing March Hare with Rubygems
  • Installing Sneakers
  • Creating queues and exchanges with each library
  • Publishing to a queue in each library
  • Consuming from queues in each library
  • Creating workers in Sneakers

Bunny and March Hare are barebones libraries. Sneakers is a job processing library built on top of RabbitMQ that offers connection profiles and handles connection failures.

Installing RabbitMQ Clients in Ruby

Install your chosen client from the Rubygems package manager, a specialized repository where. Ruby stores libraries in gems.

Use the following command to install the Bunny library:

gem install bunny

To use March Hare as your client, run:

gem install marche_hare

March Hare only works in JRuby. Check your version of Ruby by running:

ruby --version

The result should be similar to:

jruby 9.2.12.0 (2.5.7) 2020-07-01 db01a49ba6 OpenJDK 64-Bit Server VM 25.262-b10 on
1.8.0_262-b10 +jit [linux-x86_64]

You need to install JRuby if you have not already done so. Use the windows installer or, in Linux, run:

rvm install jruby

You can use sneakers as a work processor, publishing messages from either tool. Install sneakers by running:

gem install sneakers

Make sure that you have the most recent version of Ruby and Rubygems installed if you want to use the latest features. Each RabbitMQ client is in active development.

Publishing and Consuming messages with Bunny

The Bunny library gives you access to the AMQP protocol over Ruby. You have to consume and publish to queues from scratch. Create an exchange and queue as follows:

require “bunny”

conn = Bunny.new “amqps://user:password@host/your_vhost”
conn.start

channel = conn.create_channel
exchange = channel.direct(“test_exchange”)
q = channel.queue(“test_queue”, :auto_delete => true).bind(exchange, :routing_key => “test_key”)

Publish to the newly created test_queue:

exchange.publish(“Hello World!”, :routing_key => “test_key”)

You can now consume from the bunny_queue:

require “bunny”

conn = Bunny.new “amqps://user:password@host/your_vhost”
conn.start

channel = conn.create_channel
q = channel.queue("test_queue", :auto_delete => true)
begin
  q.subscribe(block: true) do |_delivery_info, _properties, body|
    puts "[x] Consumed message: []"
  end
rescue Interrupt => _
  connection.close
  exit(0)
end

You can set the amqp URL in an environment variable to avoid publishing it with your code:

CLOUDAMQP_URL= “amqps://user:password@host/your_vhost

Then replace the URL in your scripts with:

require “bunny”
require “dotenv/load”

conn = Bunny.new ENV[‘CLOUDAMQP_URL’]

The library closely follows AMQP version 0.9.1. While the client works in JRuby, there is a known bug that might cause high CPU use.

Publishing and Consuming Messages with March Hare

JRuby allows you to use proprietary databases with JDBC drivers, supports unicode natively, makes use of just-in-time compiling, and is up to two times faster than standard Ruby. The Marche Hare library makes use of JRuby without overly high CPU use.

Create an exchange and queue and publish messages using March Hare as follows:

require "rubygems"
require "march_hare"

conn = MarchHare.connect(:host=> '127.0.0.1', :vhost => "your_host", :user => "user", :password => "password")
ch = conn.create_channel
q = ch.queue("test_queue", :autodelete => true).bind("test_exchange", :routing_key => "test_key")
exchange = ch.direct('test_exchange')
exchange.publish("Hello World!", :routing_key => "test_key")
conn.close

Consume from the message from the queue you created:

require "rubygems"
require "march_hare"
conn = MarchHare.connect(:host=> '127.0.0.1', :vhost => "your_vhost", :user => "user", :password => "password")
ch = conn.create_channel
q = ch.queue("test_queue")
begin
  consume = q.subscribe do |metadata, payload|
    puts "Consumed message: #{payload}"
  end
rescue Interrupt => _
  conn.close
  exit(0)
end

March Hare works similarly to the bunny library with a few key differences. The connection function and response from a consumer differ.

Job Queueing with Sneakers

Many applications require complex task processing benefiting from the use of multiple machines and cores. Sneakers standardizes the work centered around the RabbitMQ publish-subscribe pattern while providing extensive metrics related to your workloads.

The client relies on a JSON configuration to set up and check the broker:

opts = {
    :amqp => "amqp://user:password@127.0.0.1",
    :vhost => 'test_vhost',
    :exchange => 'test_exchange',
    :exchange_type => :direct
}

Sneakers creates the test_exchange and any related queues when it starts.

We can now work on messages by setting up a processor for each desired queue:

require 'sneakers'
require 'sneakers/runner'

class Processor
  include Sneakers:Worker
  from_queue :default_queue,
  routing_key: 'test_key',
  exchange :test_exchange
  def work(msg)
    puts 'Received #{msg}'
  end
end

opts = {
    :amqp => "amqp://dev:rtp*4500@127.0.0.1",
    :vhost => 'test_vhost',
    :exchange => 'test_exchange',
    :exchange_type => :direct
}

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

This example waits on messages from test_queue bound to the test_exchange using the test_key. The queues and exchanges are created if they do not exist.

Publish to the queue from bunny and wait for the Processor to receive the message:

require ‘bunny’

conn = Bunny.new “amqp://user:password@host/your_vhost”
ch = conn.create_channel
exchange = ch.direct(“test_exchange”)
ch.default_exchange.publish(“Hello World!”, :routing_key => “test_key”)

Sneakers does not offer a publisher. Publishing to RabbitMQ requires the use of another tool.

RabbitMQ Clients in Ruby

Using RabbitMQ in Ruby gives you access to a robust message queueing library. We saw how to use Bunny and Sneakers in cRuby and March Hare in JRuby. Replace the URLs in these examples with your CloudAMQP URL to connect to your fully managed cloud broker.

CloudAMQP - industry leading RabbitMQ as a service

Start your managed cluster today. CloudAMQP is 100% free to try.

13,000+ users including these smart companies