Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A basic consumer example to consume a message from RabbitMQ Queue.
public class Consumer {
private final static String QUEUE_NAME = "Greet";
public static void main(String[] argv)
throws java.io.IOException,
java.lang.InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setUsername("guest");
factory.setPassword("guest");
Connection connection = factory.newConnection();
//Create a channel
Channel channel = connection.createChannel();
//Queue declare, if queue is already declared it returns a DeclareOk
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
QueueingConsumer consumer = new QueueingConsumer(channel);
//basic.consume amqp command to consume the message from the queue
channel.basicConsume(QUEUE_NAME, true, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment