RabbitMQ Hello World Example using bunny gem

Install the bunny gem.

gem install bunny

In the IRB:

require "bunny"

This example uses Bunny version 2.14.2.

 => "2.14.2" 

Create a connection to RabbitMQ:

connection = Bunny.new
  #<Bunny::Session:0x7fddea1845f0 guest@, vhost=/, addresses=[]> 

Start the connection:


Create a channel:

channel = connection.create_channel
 => #<Bunny::Channel:70295558133600 @id=1 @connection=#<Bunny::Session:0x7fddea1845f0 guest@, vhost=/, addresses=[]>> @open=true 

Create a test queue:

q  = channel.queue("test")
 # <Bunny::Queue:0x7fddeb8d12d0 @name="test" channel=#<Bunny::Channel:70295558133600 @id=1 @connection=#<Bunny::Session:0x7fddea1845f0 guest@, vhost=/, addresses=[]>> @open=true @durable= @auto_delete= @exclusive= @arguments=>

Publish a message to the queue:

q.publish("Hello, everybody!")
 # <Bunny::Queue:0x7fddeb8d12d0 @name="test" channel=#<Bunny::Channel:70295558133600 @id=1 @connection=#<Bunny::Session:0x7fddea1845f0 guest@, vhost=/, addresses=[]>> @open=true @durable= @auto_delete= @exclusive= @arguments=>

Read the message from the queue:

delivery_info, metadata, payload = q.pop
 => [{:delivery_tag=>#<Bunny::VersionedDeliveryTag:0x00007fddea075650 @tag=1, @version=0>, :redelivered=>false, :exchange=>"", :routing_key=>"test", :channel=>#<Bunny::Channel:70295558133600 @id=1 @connection=#<Bunny::Session:0x7fddea1845f0 guest@, vhost=/, addresses=[]>> @open=true}, {:content_type=>"application/octet-stream", :delivery_mode=>2, :priority=>0}, "Hello, everybody!"] 

Inspect the delivery_info:

 # => {:delivery_tag=>#<Bunny::VersionedDeliveryTag:0x00007fddea075650 @tag=1, @version=0>, :redelivered=>false, :exchange=>"", :routing_key=>"test", :channel=>#<Bunny::Channel:70295558133600 @id=1 @connection=#<Bunny::Session:0x7fddea1845f0 guest@, vhost=/, addresses=[]>> @open=true}

Inspect the metadata:

# {:content_type=>"application/octet-stream", :delivery_mode=>2, :priority=>0}

Inspect the payload:

  # "Hello, everybody!"
 puts "This is the message: #{payload}"
# This is the message: Hello, everybody!

In this article, we saw how easy to write a simple hello world program using the bunny gem to publish and consume a message to RabbitMQ.


Bunny Getting Started

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.