2012-10-05 68 views
1

我目前正在努力解決一個公平的簡單問題。我想接收來自RabbitMQ的消息,並將其轉換爲字符串(或稍後的json對象)。但我得到的只是字節。將消息從RabbitMQ轉換爲字符串/ json

消息對象顯示本身作爲一個字符串,方式

(Body:'{"cityId":644}'; ID:null; Content:application/json; Headers:{}; Exchange:; RoutingKey:pages.type.index; Reply:null; DeliveryMode:NON_PERSISTENT; DeliveryTag:1) 

的配置類(使用彈簧)

@Configuration 
public class RabbitConfiguration { 

    @Bean 
    public CachingConnectionFactory connectionFactory() { 
     CachingConnectionFactory connectionFactory = new CachingConnectionFactory("www.example.com"); 
     connectionFactory.setUsername("xxxx"); 
     connectionFactory.setPassword("xxxx"); 
     return connectionFactory; 
    } 

    @Bean 
    public MessageConverter jsonMessageConverter(){ 
     JsonMessageConverter jsonMessageConverter = new JsonMessageConverter(); 
     return jsonMessageConverter; 
    } 

    @Bean 
    public SimpleMessageListenerContainer messageListenerContainer(){ 
     SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory()); 
     container.setAutoStartup(false); 
     container.setQueues(indexQueue()); 
     container.setConcurrentConsumers(1); 
     container.setAcknowledgeMode(AcknowledgeMode.AUTO); 
     container.setMessageListener(new MessageListenerAdapter(pageListener(), jsonMessageConverter())); 
     return container; 
    } 

    @Bean 
    public Queue indexQueue(){ 
     return new Queue("pages.type.index"); 
    } 

    @Bean 
    public MessageListener pageListener(){ 
     return new PageQueueListener(); 
    } 

} 

和消息監聽

public class PageQueueListener implements MessageListener { 

    public void onMessage(Message message) { 
     System.out.println(message); 
     System.out.println(message.getBody()); 
    } 
} 

我的問題是,那是ge tBody()方法顯示[B @ 4dbb73b0因此沒有任何轉換。無論是一個字符串,也不JSON對象:(

我覺得自己很蠢,但我不能在這裏找到一個解決方案

回答

7

message.getBody()返回byte[]

嘗試:

byte[] body = message.getBody(); 
System.out.println(new String(body)); 
+3

你即將在開玩笑的時候......那有用,但是MessageConverter怎麼樣,不會做任何事情? – MatthiasLaug

+1

另外,如果你看看'org.springframework.amqp.core.Message'的源代碼,你會發現一個方法簽名'私人字符串getBod yContentAsString()'它是這樣做的:'return new String(body,ENCODING);'...因此,這應該足夠了:'System.out.println(new String(message.getBody(),Charset.defaultCharset ()。名稱()))' – pulkitsinghal