2016-06-23 77 views
0

我試圖發送消息,並使用獲得的響應下面的代碼無法處理來自template.convertSendAndReceive()

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

您的問題,您使用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; 

即使你​​是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。