Passing POJOs in RabbitMQ

The secret to passing POJOs in RabbitMQ is first converting them to JSON. In this post we'll look at how to do that using the NixMash Bootique RabbitMQ Demo Application as a reference.

Our POJO is a Reservation object, with a UUID id field, a String name field, and a Timestamp createdDateTime field.

You will notice the Jackson annotations. That's because another secret to using POJOs with RabbitMQ is that while RabbitMQ has a handy JSONWriter Utility, you'll probably want to use Jackson to convert objects with anything other than simple data types.

Using the RabbitMQ JSONWriter Utility:

Using Jackson:

We obviously want to see the 2nd version of Reservation on the receiving end of the RabbitMQ Queue.

Adding Jackson

Here is our dependency addition.

Packaging the POJO for Sending

Here is the code for packaging and sending the POJO to the RabbitMQ Queue. We're using Bootique to create the Connection and Channel. The only thing different in working with the POJO in Jackson as we normally would is that we need to additionally convert the JSON to a Byte Array.

Processing the POJO on the Receiving End

Here is the scene on the back end of the Queue. Here we will use the RabbitMQ JSONReader Utility, where converting the Byte[] body contents to a Reservation object is a snap.

What the Package Body Looks Like

Here is what the body of the message looks like on both ends of the Queue.

Sending...

Enter a message or a reservation name in {brackets}. [ENTER] to quit: {Big Bob}

 [x] Sent '{"id":"0f2bdd12-18e0-4ec2-b1e5-0c8fb9c36e49",
        "name":"Big Bob",
        "createdDateTime":"11-14-2017 08:44:18:916"}'

Received!

 [x] Received 'Reservation{id=0f2bdd12-18e0-4ec2-b1e5-0c8fb9c36e49,
                    name='Big Bob',
                    createdDateTime=2017-11-14 03:44:18.916}
                    [at] 11-14-2017 03:44:29:027 PM EST'
 [x] Processing the reservation with name: Big Bob
 [x] Done

Source Code Notes for this Post

Source code discussed in this post is found in my Bootique RabbitMQ Demo app on GitHub.

Posted November 14, 2017 04:15 PM EST

More Like This Post