Not able to process response received from template.convertSendAndReceive()

流过昼夜 提交于 2019-12-11 23:18:51

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/37988739/not-able-to-process-response-received-from-template-convertsendandreceive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!