Last active
August 29, 2015 13:56
-
-
Save fxg42/9228670 to your computer and use it in GitHub Desktop.
RabbitMQ HelloWorld
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
to run :