AMQP Ruby Client
The recommended Ruby client is amqp-client.rb. It has no dependencies, reconnects on its own, and recovers consumers after a reconnect. Install it with:
gem install amqp-client
Publish and consume
The example reads the broker URL from BROKER_URL and falls back to a local LavinMQ at amqp://guest:guest@localhost.
Save the connection helper as amqp.rb:
require "amqp-client"
module Amqp
def self.client
AMQP::Client.new(ENV.fetch("BROKER_URL", "amqp://guest:guest@localhost")).start
end
end
Save the publisher as publisher.rb:
require_relative "amqp"
module Publisher
# Messages are persistent and wait for a publisher confirm by default
def self.publish(client, queue, message)
client.queue(queue).publish(message)
puts " [x] Sent #{message.inspect}"
end
end
if __FILE__ == $PROGRAM_NAME
client = Amqp.client
Publisher.publish(client, "hello", "Hello world!")
client.stop
end
Save the consumer as worker.rb in the same directory:
require_relative "amqp"
module Worker
# The message is acked when the block returns, and requeued if it raises
def self.consume(client, queue, &handler)
client.queue(queue).subscribe(prefetch: 10) do |msg|
handler.call(msg.body)
end
end
end
if __FILE__ == $PROGRAM_NAME
client = Amqp.client
Worker.consume(client, "hello") { |message| puts " [x] Received #{message.inspect}" }
puts " [*] Waiting for messages. To exit press CTRL+C"
begin
sleep
rescue Interrupt
client.stop
end
end
Run ruby worker.rb in one terminal and ruby publisher.rb in another.
The full, runnable example lives in ruby/amqp-client in cloudamqp/examples, and CI tests it against LavinMQ.
Good to know
- Messages get acked after the block returns. If the block raises, the client rejects the message and LavinMQ requeues it. A message can arrive twice after a reconnect, so keep handlers idempotent.
- Set a prefetch limit.
subscribedefaults to a prefetch of 1. Raise it, as insubscribe(prefetch: 10), for higher throughput without buffering more than a consumer can handle. - Use
amqps://for TLS. The client verifies the server certificate and hostname.
The amqp-client.rb README covers codecs, RPC and the low-level API.
Other Ruby clients
Ready to take the next steps?
Managed LavinMQ instance via CloudAMQP
LavinMQ has been built with performance and ease of use in mind - we've benchmarked a throughput of about 1,000,000 messages/sec. You can try LavinMQ without any installation hassle by creating a free instance on CloudAMQP. Signing up is a breeze.
Get started with CloudAMQP ->Help and feedback
We welcome your feedback and are eager to address any questions you may have about this piece or using LavinMQ. Join our Slack channel to connect with us directly. You can also find LavinMQ on GitHub.