LavinMQ with Ruby

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

Code example using Bunny

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

We begin by adding the environment variable HOST_URL to our .env file.

➜ vim .env
CLOUDAMQP_URL="amqps://user:password@host/user"
~

Then, we add these gems to our Gemfile if they are not yet added.

➜ vim Gemfile
source 'https://rubygems.org'
ruby '2.7.0'
gem 'bunny'
gem 'dotenv'
~

Further, we create a script and name it publish.rb. In the publish.rb script we will write down a simple example on how to publish a message.

require "bunny"
require "dotenv/load"

connection = Bunny.new ENV['CLOUDAMQP_URL']
connection.start # Start a connection with the CloudAMQP server
channel = connection.create_channel # Declare a channel
queue = channel.queue("bunny_queue") # Declare a queue

# Declare a default direct exchange which is bound to all queues
exchange = channel.exchange("")

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

connection.close # Finally, close the connection

Then, we create another script and name it subscribe.rb. In the subscribe.rb script we will write down a simple example on how to consume a message.

require "bunny"
require "dotenv/load"

connection = Bunny.new ENV['CLOUDAMQP_URL']
connection.start  # Start a connection with the CloudAMQP server
channel = connection.create_channel # Declare a channel
queue = channel.queue("bunny_queue") # Declare a queue

begin # Consume messages
  puts ' [*] Waiting for messages. To exit press CTRL+C'
  queue.subscribe(block: true) do |_delivery_info, _properties, body|
    puts " [x] Consumed message: []"
  end
rescue Interrupt => _
  connection.close # Close the connection
  exit(0)
end

Finally, in each terminal window, we run the scripts subscribe.rb and publish.rb respectively.

➜ ruby publish.rb
➜ ruby subscribe.rb
> [*] Waiting for messages. To exit press CTRL+C
> [x] Consumed message: Hello everybody!