问题描述:

Java spring boot项目监听rabbitmq消息时报错了,之前不报错,当将服务拆分成dubbo微服务后,报错了,如下:

Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token at [Source: (String)"{"messageId":"EvgdC1dbzcECRC6Cjm7CXZHHw8vdwEyz","version":"1","deviceId":"777381400045217","properties":{"{\"GMWB.flue_temp\":\"29.7\"}","timestamp":"1773907491"}"; line: 1, column: 1]

问题分析:

如下图,在下面的代码里,监听器方法参数是 String content,这和上面报错里的 Cannot deserialize instance of java.lang.String`` 完全对应上了:

// (以前能跑,现在跑不了)
@RabbitListener(containerFactory = "customContainerFactory", queues = "#{queueName}")
public void processMqMsg(String content, Channel channel, Message message) throws IOException {
    analysisService.handleMqMsg(content);
}
  • 以前能跑的原因

        之前的 MessageConverterSimpleMessageConverter,它会直接把消息体字节数组转成 String,所以 String content 能正常接收。✅

  • 现在报错的原因

        切换 Dubbo 后:可能引入了新的自动配置,把 MessageConverter 替换成了 Jackson2JsonMessageConverter → 尝试把 JSON 对象转 String

解决方案:

改回 SimpleMessageConverter(最快恢复):
既然你业务里就是要 String content,那直接让 RabbitMQ 用简单字符串转换器,不要用 JSON 转换器。

@Bean
public MessageConverter simpleMessageConverter() {
    return new SimpleMessageConverter(); // 直接转成 String,和你以前一样
}

// 或者在 customContainerFactory 里指定
@Bean
public SimpleRabbitListenerContainerFactory customContainerFactory(
        ConnectionFactory connectionFactory,
        @Qualifier("simpleMessageConverter") MessageConverter messageConverter) {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setMessageConverter(messageConverter); // 用 SimpleMessageConverter
    // ... 其他配置
    return factory;
}

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐