Search code examples
javaspringrabbitmqmessageamqp

Spring AMQP Headers are returned as String only


I am using Java Spring with version 2.0.0 Snapshot of AMQP. I create an AMQP message, send it. In another service I am receiving the message correctly, except the headers instead of receiving type Object, every header is of type String.

Publisher Code:

Message responseMessage = MessageBuilder
    .withBody(SerializationUtils.serialize(person))
    .setContentType(MessageProperties.CONTENT_TYPE_SERIALIZED_OBJECT)
    .setHeader("STUDENT_TYPE", "New") // Not part of person object but related
    .setHeader("PET", getPet()) // This is a pet object
    .build();
rabbitTemplate.send(responseMessage);

Consumer Code:

Object messageBody = SerializationUtils.deserialize(amqpMessage.getBody());
Person person = (Person)messageBody;
MessageProperties properties = amqpMessage.getMessageProperties();
String type = properties.getHeaders().get("STUDENT_TYPE").toString();
Pet pet = (Pet)properties.getHeaders().get("PET");

When I run the above code, I will fail on the last line of the consumer code with the error: Cannot cast String to Pet. The message comes across ok, except every header is of type String when received in the consumer code.

USAGE: MessageBuilder.setHeader(String Key, Object Value);

USAGE: Properties.getHeaders() returns Map<String,Object>

Every header has key/value pair of type String/Object. The work around I have in place is also serializing an header I would like to pass non-string/integer values for, but this seems to be besides the point of the header. Am I missing something?


Solution

  • You need to serialize your Pet to a string, and deserialize it when you get it in another service. E.g. you can use fasterxml Jackson and serialize it to JSON string