RabbitMQ消费消息坑:failed to convert serialized Message content | jiuchengi-cnblogs
org.springframework.amqp.rabbit.support.ListenerExecutionFailedException: Failed to convert message
at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:156) ~[spring-rabbit-2.4.5.jar:2.4.5]
...
Caused by: org.springframework.amqp.support.converter.MessageConversionException: failed to convert serialized Message content
at org.springframework.amqp.support.converter.SimpleMessageConverter.fromMessage(SimpleMessageConverter.java:117) ~[spring-amqp-2.4.5.jar:2.4.5]
at
...
Caused by: java.lang.IllegalStateException: Could not deserialize object type
at org.springframework.amqp.utils.SerializationUtils.deserialize(SerializationUtils.java:97) ~[spring-amqp-2.4.5.jar:2.4.5]
at org.springframework.amqp.support.converter.SimpleMessageConverter.fromMessage(SimpleMessageConverter.java:113) ~[spring-amqp-2.4.5.jar:2.4.5]
... 16 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.cauli.file.model.dto.file.FileSearchDTO
at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[na:1.8.0_221]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_221]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) ~[na:1.8.0_221]
...
这个异常信息表明在处理消息时出现了问题,具体地说,它是由于消息内容的反序列化失败引起的。以下为关键信息:
org.springframework.amqp.rabbit.support.ListenerExecutionFailedException: Failed to convert message
Caused by: org.springframework.amqp.support.converter.MessageConversionException: failed to convert serialized Message content
Caused by: java.lang.IllegalStateException: Could not deserialize object type
Caused by: java.lang.ClassNotFoundException: com.cauli.file.model.dto.file.FileSearchDTO
根据异常信息的内容,问题似乎是由于反序列化消息内容时找不到类 com.cauli.file.model.dto.file.FileSearchDTO
导致的。
我目前生产者和消费者都有一个FileSearchDTO
对象,内容是一模一样的包括序列化,可就是消费者接收时报序列化错误。
把这个对象放到公共模块,然后生产者和消费者服务引入这个公共模块,生产者和消费者发送和消费时共用一个对象。这样完全保证了两个项目中JavaBean是一致的,所以能解决反序列失败的问题。
缺点:局限性太小,这种模式生产者和消费者只能在同一个微服务下才能使用
生产者添加配置:
/**
* RabbitMQ配置
*
* @author Tang
* @version 1.0
* @date 2022/05/02 23:23:27
*/
@Configuration
public class RabbitMQConfig implements InitializingBean {
/**
* 自动注入RabbitTemplate模板
*/
@Resource
private RabbitTemplate rabbitTemplate;
/**
* 发送消息JSON序列化
*/
@Override
public void afterPropertiesSet() {
//使用JSON序列化
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
}
}
消费者添加配置:
/**
* RabbitMQ配置
*
* @author Tang
* @version 1.0
* @date 2022/05/02 23:23:27
*/
@Configuration
public class RabbitMQConfig {
@Bean
public MessageConverter jsonMessageConverter(ObjectMapper objectMapper) {
return new Jackson2JsonMessageConverter(objectMapper);
}
}