I am trying to send message and receive response using following code
MessageProperties props =MessagePropertiesBuilder.newInstance().setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
.setMessageId("MSG12345").setHeader("type", "type1").setCorrelationId(UUID.randomUUID().toString().getBytes()).build();
Message message = MessageBuilder.withBody(input.getBytes()).andProperties(props).build();
Message response = (Message) template.convertSendAndReceive("key", message);
But, its is throwing ava.lang.ClassCastException: java.lang.String cannot be cast to org.springframework.amqp.core.Message
May be because, I am sending request using java (spring-amqp) program and the receiver is a python (pika) program.
Recevier is sending me a JSON object dumped in string format but I am not able to handle it.
Your problem that you use RabbitTemplate.convertSendAndReceive()
:
/**
* Basic RPC pattern with conversion. Send a Java object converted to a message to a default exchange with a
* specific routing key and attempt to receive a response, converting that to a Java object. Implementations will
* normally set the reply-to header to an exclusive queue and wait up for some time limited by a timeout.
*
* @param routingKey the routing key
* @param message a message to send
* @return the response if there is one
* @throws AmqpException if there is a problem
*/
Object convertSendAndReceive(String routingKey, Object message) throws AmqpException;
Even if your payload
is Message
and we we have:
protected Message convertMessageIfNecessary(final Object object) {
if (object instanceof Message) {
return (Message) object;
}
return getRequiredMessageConverter().toMessage(object, new MessageProperties());
}
It converts a reply
into a target object from body
:
return this.getRequiredMessageConverter().fromMessage(replyMessage);
and don't return Message
as you expected.
So, you really have to cast to String
and deal with your JSON already on your own.