Using RabbitMQ Java Client to send AMQP Messages to a AMQP Broker

Introduction

RabbitMQ is an open source message broker which implements AMQP messaging protocol. It also has multiple client libraries (Java, .NET, Erlang) which can be used to send/recieve AMQP messages to/from an AMQP broker.

In this post I’m going to explain how to use the RabbitMQ Java Client Library to send and Receive messages. Since RabbitMQ also can act as an AMQP server, I’ll be using it in this post.

Configuring RabbitMQ Server

This documentation explains about how to configure RabbitMQ server in multiple OS environments. You have to use one of it accordingly and configure it.

Using RabbitMQ Maven dependency

Creating a maven project by using the rabbitmq maven dependency is relatively easy. This library is available as a maven dependency at central maven repository. Use the following maven dependency in your project.

<dependency>
  <groupId>com.rabbitmq</groupId>
  <artifactId>amqp-client</artifactId>
  <version>3.0.4</version>
</dependency>

Publishing an AMQP message

The following code segment shows the relevant parts needed in order to publish an AMQP message to the broker.

ConnectionFactory factory = new ConnectionFactory();
factory.setHost(host);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

try {
    channel.queueDeclare("Queue1", false, false, false, null);
    channel.exchangeDeclare("Exchange1", "direct", true);
    channel.queueBind("Queue1", "Exchange1", routingKey);
    String message = "This is a test message";
    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
    builder.messageId("123456789");
    channel.basicPublish("Exchange1", "Queue1", builder.build(), message.getBytes());

} catch (IOException e) {
    e.printStackTrace();
} finally {
    channel.close();
    connection.close();
}

In here we specify the queue name with the channel. If the queue is not found on broker, then a new queue will be created. Then you have to define an exchange on which the queue is bound.

We also can add properties to the message before publishing. This is done by using AMQP.BasicProperties() instance. The following are the set of properties that can be added to an AMQP message.

“contentType, contentEncoding, headers, deliveryMode, priority, correlationId, replyTo, expiration, messageId, timestamp, type, userId, appId, clusterId”

Apart from the above properties, if you want add custom properties, you can do so with the “headers” Map as key value pairs.

Consuming an AMQP Message

The following code segment shows how to consume messages from a queue in a AMQP broker.

ConnectionFactory factory = new ConnectionFactory();
factory.setHost(host);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("Queue1", false, false, false, null);
channel.exchangeDeclare("Exchange1", "direct", true);
channel.queueBind("Queue1", "Exchange1", routingKey);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume("Queue1", true, consumer);

while (true) {
     QueueingConsumer.Delivery delivery = consumer.nextDelivery();
     String message = new String(delivery.getBody());
     System.out.println("Message Received : '" + message + "'");
}

Using the above, you can consume the messages that comes to the queue name “Queue1”. You have to use the correct queue and exchange names. The object instance “QueueingConsumer” is what does the actual consuming of messages from queue. The call from the consumer, “consumer.nextDelivery()”, is a blocking which waits until a message gets delivered from the queue.

There can be situations where the AMQP server is running on default port with default user account. So when configuring the connection factory, you can also define those values accordingly.

For example :

ConnectionFactory factory = new ConnectionFactory()
factory.setHost(host);
factory.setPort(port);
factory.setUsername(user);
factory.setPassword(password);
factory.setVirtualHost(virtualHost);

This shows how to set different configuration values, such as port, username, password, etc for a connection factory.

Advertisements

About kishanthan

I’m currently working as a Software Engineer at WSO2, an open source software company. I hold an Engineering degree, majoring in Computer Science & Engineering field, from University of Moratuwa, Sri Lanka.
This entry was posted in How to, Java, RabbitMQ and tagged , , , , , , . Bookmark the permalink.

One Response to Using RabbitMQ Java Client to send AMQP Messages to a AMQP Broker

  1. Pingback: AMQP Transport for WSO2 ESB based on RabbitMQ Java Client | Kishanthan's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s