CloudAMQP with Clojure Getting started

Langohr is a full featured and well maintained Clojure wrapper for Java's AMQP library.

To use it put [com.novemberain/langohr "2.3.2"] (look up the current latest version at Clojars ) in your project.clj file and run lein deps.

Langohr has great documentation at which we recommend you do check out. Below follows a simple pub/sub example.

(ns clojure-amqp-example.core
  (:require [langohr.core      :as rmq]
            [   :as lch]
            [langohr.queue     :as lq]
            [langohr.consumers :as lc]
            [langohr.basic     :as lb]))

(defn message-handler
  [ch {:keys [content-type delivery-tag] :as meta} ^bytes payload]
    (format "[consumer] Received a message: %s, delivery tag: %d, content type: %s"
            (String. payload "UTF-8") delivery-tag content-type)))

(def url (get (System/getenv) "CLOUDAMQP_URL" "amqp://guest:guest@localhost"))

(defn -main
  [& args]
  (let [conn  (rmq/connect {:uri url}) ;; Connect to our URL
        ch    (lch/open conn) ;; Open a channel
        qname "langohr.examples.hello-world"]
    (println "[main] Connected")
    ;; Create a queue
    (lq/declare ch qname {:exclusive false :auto-delete true})
    ;; Subscribe to the queue
    ;; The message-handler will be executed for each message
    (lc/subscribe ch qname message-handler {:auto-ack true})
    ;; Enqueue a msg to the queue via the default exchange
    ;; All queues are bound to it with their name as routing key
    (lb/publish ch "" qname "Hello!" {:content-type "text/plain"})
    (Thread/sleep 2000)
    (println "[main] Disconnecting...")
    ;; Close the connection (channels will automatically be closed too)
    (rmq/close conn)))