Skip to content

Instantly share code, notes, and snippets.

@fxg42
Last active August 29, 2015 13:56
Show Gist options
  • Save fxg42/9228670 to your computer and use it in GitHub Desktop.
Save fxg42/9228670 to your computer and use it in GitHub Desktop.
RabbitMQ HelloWorld
// Copyright (C) 2014 François-Xavier Guillemette
//
// This program is free software. It comes without any warranty, to
// the extent permitted by applicable law. You can redistribute it
// and/or modify it under the terms of the Do What The Fuck You Want
// To Public License, Version 2, as published by Sam Hocevar. See
// http://www.wtfpl.net/ for more details.
@Grab('com.rabbitmq:amqp-client:2.8.1')
import com.rabbitmq.client.*
// Create the connection
def factory = new ConnectionFactory()
factory.setUri("amqp://guest:guest@localhost")
def connection = factory.newConnection()
def channel = connection.createChannel()
// Configure the channel
def prefetchCount = 1
channel.basicQos(prefetchCount)
// Create the queue
def queueName = 'hello'
def isDurable = false
def isExclusive = false
def isAutoDelete = false
def queueArguments = null
channel.queueDeclare(queueName, isDurable, isExclusive, isAutoDelete, queueArguments)
// Produce a message
def messagePersistence = null // MessageProperties.PERSISTENT_TEXT_PLAIN
def exchangeName = '' // default, nameless exchange
def routingKey = queueName
def message = 'Mr. Rabbit says Hello.'
channel.basicPublish(exchangeName, routingKey, messagePersistence, message.bytes)
// Consume messages
def isAutoAck = false
def consumer = new QueueingConsumer(channel)
channel.basicConsume(queueName, isAutoAck, consumer)
while (true) {
def delivery = consumer.nextDelivery()
def received = new String(delivery.body, 'UTF-8')
println "received <${received}>"
if (! isAutoAck) {
def acknowledgesMultiple = false
channel.basicAck(delivery.envelope.deliveryTag, acknowledgesMultiple)
}
}
// We never get here, but cleanup anyhow
channel.close()
connection.close()
@fxg42
Copy link
Author

fxg42 commented Feb 27, 2014

to run :

$ git clone https://gist.github.com/9228670.git && cd 9228670/
$ groovy hello.groovy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment