Skip to content

Connect FlowMQ with AMQP Ruby Client

FlowMQ's native support for AMQP 0.9.1 makes it an excellent choice for Ruby applications that need reliable, asynchronous messaging. This guide will walk you through using bunny, a popular and feature-rich AMQP client for Ruby, to connect to FlowMQ, declare queues, publish messages, and subscribe to them.

Prerequisites

Before you begin, ensure you have the following:

  • A running instance of FlowMQ.
  • Ruby 2.5 or later installed.
  • Bundler for managing gems.

Installation

Add the bunny gem to your project's Gemfile and then install it using Bundler.

ruby
# Gemfile
source "https://rubygems.org"

gem "bunny"

Then, run bundle install from your terminal:

bash
bundle install

Connecting to FlowMQ

First, you need to start a connection to your FlowMQ broker. Once connected, you can open a channel to perform AMQP operations.

ruby
require "bunny"

# Start a connection
conn = Bunny.new
conn.start
puts "Connected to FlowMQ!"

# Create a channel
ch = conn.create_channel

Declaring a Queue

For this example, we'll declare a queue and publish messages directly to it using the default exchange.

ruby
# Declare a queue
q = ch.queue("hello-ruby")

Publishing a Message

Now, you can publish a message to the default exchange. The routing key must be the name of the queue for the message to be delivered.

ruby
# Publish a message to the default exchange
ch.default_exchange.publish("Hello FlowMQ from Bunny!", routing_key: q.name)
puts " [x] Sent 'Hello FlowMQ from Bunny!'"

Subscribing and Consuming Messages

To receive messages, you can subscribe to a queue. The provided block will be executed for each message that arrives.

ruby
puts " [*] Waiting for messages. To exit press CTRL+C"
begin
  q.subscribe(block: true) do |_delivery_info, _properties, body|
    puts " [x] Received #{body}"
  end
rescue Interrupt => _
  ch.close
  conn.close
end

Full Example

Here are two separate scripts, one for publishing and one for consuming, to demonstrate a complete workflow.

Publisher (publisher.rb)

ruby
require "bunny"

conn = Bunny.new
conn.start

ch = conn.create_channel
q  = ch.queue("bunny.examples.hello")

ch.default_exchange.publish("Hello World!", routing_key: q.name)
puts " [x] Sent 'Hello World!'"

conn.close

Consumer (consumer.rb)

ruby
require "bunny"

conn = Bunny.new
conn.start

ch = conn.create_channel
q  = ch.queue("bunny.examples.hello")

puts " [*] Waiting for messages. To exit press CTRL+C"
begin
  q.subscribe(block: true) do |delivery_info, properties, body|
    puts " [x] Received #{body}"
  end
rescue Interrupt => _
  conn.close
end

Additional Resources

  • For more advanced features, error handling, and examples, refer to the official Bunny guides.
  • Explore FlowMQ's advanced features for AMQP integration.