Book Image

RabbitMQ Cookbook

Book Image

RabbitMQ Cookbook

Overview of this book

RabbitMQ is an open source message broker software (sometimes called message-oriented middleware) that implements the Advanced Message Queuing Protocol (AMQP). The RabbitMQ server is written in the Erlang programming language and is built on the Open Telecom Platform framework for clustering and failover. Messaging enables software applications to connect and scale. Applications can connect to each other as components of a larger application or to user devices and data. RabbitMQ Cookbook touches on all the aspects of RabbitMQ messaging. You will learn how to use this enabling technology for the solution of highly scalable problems dictated by the dynamic requirements of Web and mobile architectures, based for example on cloud computing platforms. This is a practical guide with several examples that will help you to understand the usefulness and the power of RabbitMQ. This book helps you learn the basic functionalities of RabbitMQ with simple examples which describe the use of RabbitMQ client APIs and how a RabbitMQ server works. You will find examples of RabbitMQ deployed in real-life use-cases, where its functionalities will be exploited combined with other technologies. This book helps you understand the advanced features of RabbitMQ that are useful for even the most demanding programmer. Over the course of the book, you will learn about the usage of basic AMQP functionalities and use RabbitMQ to let decoupled applications exchange messages as per enterprise integration applications. The same building blocks are used to implement the architecture of highly scalable applications like today's social networks, and they are presented in the book with some examples. You will also learn how to extend RabbitMQ functionalities by implementing Erlang plugins. This book combines information with detailed examples coupled with screenshots and diagrams to help you create a messaging application with ease.
Table of Contents (19 chapters)
RabbitMQ Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Using message properties


In this example we will show how an AMQP message is divided, and how to use message properties.

You can find the source at Chapter01/Recipe11/Java_11/.

Getting ready

To use this recipe you will need to set up the Java development environment as indicated in the Introduction section.

How to do it…

In order to access the message properties you need to perform the following steps:

  1. Declare a queue:

    channel.queueDeclare(MyQueue, false, false, false,null);
  2. Create a BasicProperties class:

    Map<String,Object>headerMap = new HashMap<String,   Object>();
    headerMap.put("key1", "value1");
    headerMap.put("key2", new Integer(50) );
    headerMap.put("key3", new Boolean(false));
    headerMap.put("key4", "value4");
    
    BasicProperties messageProperties = new BasicProperties.Builder()
    .timestamp(new Date())
    .contentType("text/plain")
    .userId("guest")
    .appId("app id: 20")
    .deliveryMode(1)
    .priority(1)
    .headers(headerMap)
    .clusterId("cluster id: 1")
    .build();
  3. Publish a message with basic properties:

    channel.basicPublish("",myQueue,messageProperties,message.getBytes())
  4. Consume a message and print the properties:

    System.out.println("Property:" + properties.toString());

How it works…

The AMQP message (also called content) is divided into two parts:

  • Content header

  • Content body (as we have already seen in previous examples)

In step 2 we create a content header using BasicProperties:

Map<String,Object>headerMap = new HashMap<String, Object>();
BasicProperties messageProperties = new BasicProperties.Builder()
.timestamp(new Date())
.userId("guest")  
.deliveryMode(1)
.priority(1)
.headers(headerMap)
.build();

With this object we have set up the following properties:

  • timestamp: This is the message time stamp.

  • userId: This is the broker with whom the user sends the message (by default, it is "guest"). In the next chapter we'll see the users' management.

  • deliveryMode: If set to 1 the message is nonpersistent, if it is 2 the message is persistent (you can see the recipe Connecting to the broker).

  • priority: This defines the message priority, which can be 0 to 9.

  • headers: A HashMap<String, Object> header, you are free to use it to enter your custom fields.

Tip

The RabbitMQ BasicProperties class is an AMQP content header implementation. The attribute of BasicProperties can be built using BasicProperties.Builder()

The header is ready and we can send a message using channel.basicPublish("",myQueue, messageProperties,message.getBytes()), where messageProperties is the message header and message is the message body.

In step 4 the consumer gets a message:

public void handleDelivery(String consumerTag,Envelope envelope, 
BasicProperties properties,byte[] body) throws java.io.IOException {
System.out.println("***********message header****************");
System.out.println("Message sent at:"+ properties.getTimestamp());
System.out.println("Message sent by user:"+ properties.getUserId());
System.out.println("Message sent by App:"+properties.getAppId());
System.out.println("all properties :" + properties.toString());
System.out.println("**********message body**************");
String message = new String(body);
System.out.println("Message Body:"+message);
}

The parameter properties contains the message header and body contains its body.

There's more…

Using message properties we can optimize the performance. Writing audit information or log information into the body is a typical error, because the consumer should parse the body to get them.

The body message must only contain application data (for example, a Book class), while the message properties can host other information related to the messaging mechanics or other implementation details.

For example, if the consumer wants to log when a message has been sent you can use the timestamp attribute, or if the consumer needs to distinguish a message according to a custom tag, you can put it in the headers HashMap property.

See also

The class MessageProperties contains some pre-built BasicProperties class for standard cases. Please check the official link at http://www.rabbitmq.com/releases//rabbitmq-java-client/current-javadoc/com/rabbitmq/client/MessageProperties.html

In this example we have just used some of the properties. You can get more information at http://www.rabbitmq.com/releases//rabbitmq-java-client/current-javadoc/com/rabbitmq/client/AMQP.BasicProperties.html.