Crystal with RabbitMQ and LavinMQ

We recommend amqp-client.cr. It’s small, fast and has no dependencies. Add it to shard.yml and run shards install:

dependencies:
  amqp-client:
    github: cloudamqp/amqp-client.cr

Publish and consume

Set BROKER_URL to the AMQP URL from your instance’s details page in the CloudAMQP console. Without it, the example connects to a local broker.

Save the connection, publisher and consumer helpers as example.cr:

require "amqp-client"

module Example
  # Connects to BROKER_URL. TLS connections (amqps://) verify the server certificate.
  # The client doesn't reconnect: restart the process or reconnect yourself if the connection is lost.
  def self.connect : AMQP::Client::Connection
    AMQP::Client.new(ENV.fetch("BROKER_URL", "amqp://guest:guest@localhost")).connect
  end

  # Publishes a persistent message and blocks until the broker has confirmed it
  def self.publish(ch : AMQP::Client::Channel, queue : String, message : String) : Nil
    q = ch.queue(queue, durable: true)
    props = AMQP::Client::Properties.new(content_type: "text/plain", delivery_mode: 2_u8)
    q.publish_confirm(message, props: props) || raise "Message was not confirmed"
    puts " [x] Sent '#{message}'"
  end

  # Consumes with a prefetch of 10, acking each message after the block returns
  def self.consume(ch : AMQP::Client::Channel, queue : String, &handler : String ->) : Nil
    ch.prefetch(10)
    ch.queue(queue, durable: true).subscribe(no_ack: false) do |msg|
      handler.call(msg.body_io.to_s)
      msg.ack
    end
  end
end

Save a publisher as publisher.cr:

require "./example"

conn = Example.connect
Example.publish(conn.channel, "hello", "Hello world!")
conn.close

Save a consumer as worker.cr. Subscribing starts a background fiber, so the main fiber sleeps to keep the process running:

require "./example"

conn = Example.connect
Example.consume(conn.channel, "hello") { |message| puts " [x] Received '#{message}'" }
puts " [*] Waiting for messages. To exit press CTRL+C"

Process.on_terminate do
  conn.close
  exit
end
sleep

Run crystal run worker.cr in one terminal and crystal run publisher.cr in another.

A runnable example is in crystal/amqp-client in cloudamqp/examples.

Good to know

  • Connect with the URL. AMQP::Client.new(url).connect, where the URL is the one on your instance’s details page in the CloudAMQP console. With amqps:// the server certificate is verified.
  • Set delivery_mode: 2 for persistent messages; without it messages are transient.
  • Check the result of publish_confirm. It returns false if the broker rejects the message, rather than raising.
  • Pass no_ack: false to subscribe and ack after processing. By default messages are acked on delivery, and lost if your block raises.
  • The client doesn’t reconnect. Let your process manager restart a worker whose connection is lost.
Was this page helpful?

Thanks for your feedback!