問題描述
我目前正在努力解決一個相當(dāng)簡單的問題.我想從 RabbitMQ 接收消息并將其轉(zhuǎn)換為字符串(或稍后轉(zhuǎn)換為 json 對象).但我得到的只是字節(jié).
I am currently struggling hard with a fair simple problem. I want to receive a message from RabbitMQ and have that transformed into a string (or later a json object). But all I get is bytes.
Message 對象以這種方式將自身顯示為字符串
The Message object displays itself as a string that way
(Body:'{"cityId":644}'; ID:null; Content:application/json; Headers:{}; Exchange:; RoutingKey:pages.type.index; Reply:null; DeliveryMode:NON_PERSISTENT; DeliveryTag:1)
配置類(使用spring)
The configuration class (using spring)
@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();
}
}
和消息監(jiān)聽器
public class PageQueueListener implements MessageListener {
public void onMessage(Message message) {
System.out.println(message);
System.out.println(message.getBody());
}
}
我的問題是,getBody() 方法顯示 [B@4dbb73b0 所以沒有任何東西被轉(zhuǎn)換.既不是字符串也不是 json 對象:(
my problem is, that the getBody() method displayes [B@4dbb73b0 so nothing is ever converted. Neither to a string nor to a json object :(
我覺得自己很愚蠢,但我在這里找不到解決方案
I feel stupid, but I cannot find a solution here
推薦答案
message.getBody()
返回一個byte[]
試試:
byte[] body = message.getBody();
System.out.println(new String(body));
這篇關(guān)于將消息從 RabbitMQ 轉(zhuǎn)換為字符串/json的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!