我目前正在努力解决一个公平的问题。我想从RabbitMQ收到一条消息,并将其转换为字符串(或稍后的json对象)。但我得到的只是字节。
消息对象将其自身显示为字符串
(Body:'{"cityId":644}'; ID:null; Content:application/json; Headers:{}; Exchange:; RoutingKey:pages.type.index; Reply:null; DeliveryMode:NON_PERSISTENT; DeliveryTag:1)
配置类(使用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();
}
}
和消息监听器
public class PageQueueListener implements MessageListener {
public void onMessage(Message message) {
System.out.println(message);
System.out.println(message.getBody());
}
}
我的问题是, getBody()方法显示 [B @ 4dbb73b0 ,因此无需转换任何内容。既不是字符串也不是json对象:(
我觉得很蠢,但我找不到解决方案
答案 0 :(得分:11)
message.getBody()
返回byte[]
尝试:
byte[] body = message.getBody();
System.out.println(new String(body));
答案 1 :(得分:0)
如果要解析为JSONObject,最好的方法是将RabbitMQ消息添加为String格式的StringBuilder。然后使用任何转换工具将StringBuilder解析为JSONObject。
例如:
StringBuilder sb = new StringBuilder();
sb.append(publisher.toString());
payload = (JSONObject)jsonParser.parse(sb.toString());