RabbitMQ JSON Messages with Spring Boot AMQP

This is a very well-written blog post from Java Champion Moisés Macero on working with JSON Messages. It explains how to send a JSON AMQP Message object as well as a Serialized CustomMessage POJO. Two Listener methods respond to a single rabbitTemplate.convertAndSend() call.

@RabbitListener(queues = MessagingApplication.QUEUE_GENERIC_NAME)
public void receiveMessage(final Message message) {
    log.info("Received message as generic: {}", message.toString());

@RabbitListener(queues = MessagingApplication.QUEUE_SPECIFIC_NAME)
public void receiveMessage(final CustomMessage customMessage) {
    log.info("Received message as specific class: {}", customMessage.toString());

They produce the following output:

I|CustomMessageListener   |  Received message as generic: (Body:'{"text":"Hello there!","priority":45,"secret":false}' MessageProperties [headers={__TypeId__=es.macero.CustomMessage}, timestamp=null, messageId=null, userId=null, receivedUserId=null, appId=null, clusterId=null, type=null, correlationId=null, correlationIdString=null, replyTo=null, contentType=application/json, contentEncoding=UTF-8, contentLength=0, deliveryMode=null, receivedDeliveryMode=PERSISTENT, expiration=null, priority=0, redelivered=false, receivedExchange=appExchange, receivedRoutingKey=messages.key, receivedDelay=null, deliveryTag=2, messageCount=0, consumerTag=amq.ctag-Rgj7bPH88bbBAK1fc3SarA, consumerQueue=appGenericQueue])

I|CustomMessageListener   |  Received message as specific class: CustomMessage{text='Hello there!', priority=45, secret=false}

There's also a link to the GitHub application for the post.

I should mention that with Spring Boot 2.0 a new way to handle JSON has been added to Spring Boot AMQP. From the "What's New in Spring AMQP Doc."

The RabbitTemplate and AsyncRabbitTemplate now have receiveAndConvert and convertSendAndReceiveAsType methods that take a ParameterizedTypeReference<T> argument, allowing the caller to specify the type to convert the result to. This is particularly useful for complex types or when type information is not conveyed in message headers. Requires a SmartMessageConverter such as the Jackson2JsonMessageConverter. See [receiving-messages], [request-reply], [async-template], and [json-complex] for more information.

There's a good demonstration of that in this Spring AMQP Sample Project from Gary Russell.