我正在尝试使用以下代码发送消息并接收响应
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);
但是,它正在抛出ava.lang.ClassCastException:java.lang.String无法强制转换为org.springframework.amqp.core.Message
可能是因为,我使用java(spring-amqp)程序发送请求,接收器是python(pika)程序。 Recevier向我发送了一个以字符串格式转储的JSON对象,但我无法处理它。
答案 0 :(得分:0)
您使用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;
即使您的payload
是Message
,我们也有:
protected Message convertMessageIfNecessary(final Object object) {
if (object instanceof Message) {
return (Message) object;
}
return getRequiredMessageConverter().toMessage(object, new MessageProperties());
}
它将reply
转换为body
的目标对象:
return this.getRequiredMessageConverter().fromMessage(replyMessage);
并且不会按预期返回Message
。
所以,你真的必须转发String
并自己处理你的JSON。