SpringBoot2.6.0版本的RabbitMQ反序列化异常问题:MessageConversionException. 使用同一实体类反序列化异常配置。

SpringBoot2.6.0版本的RabbitMQ反序列化异常问题:MessageConversionException. 使用同一实体类反序列化异常配置。,第1张

SpringBoot2.6.0版本的RabbitMQ反序列化异常问题:MessageConversionException. 使用同一实体类反序列化异常配置

springboot: 2.6.0
RabbitMQ 3.9.11

实体类UserInfo

private Integer id;
private String lastName;
getset

配置json序列化:

@Configuration
public class AmqpConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        return rabbitTemplate;
    }

测试:
User user=new User();
user.setId(1);
user.setUsername(“张三”);
user.setPassword(“123456”);
rabbitTemplate.convertAndSend(“amq.fanout”,“tt”,user);

Exchange	amq.fanout
Routing Key	tt
Redelivered	○
Properties	
priority:	0
delivery_mode:	2
headers:	
__TypeId__:	thing1
content_encoding:	UTF-8
content_type:	application/json
Payload
79 bytes
Encoding: string
{"id":1,"username":"战三","password":"123456","creatTime":null,"gender":null}

正常发送消息。

此时如果使用 @RabbitListener(queues = " ")
运行报错:MessageConversionException 反序列化失败了。

需要加入配置:
官方文档

@Bean
public Jackson2JsonMessageConverter jsonMessageConverter() {
    Jackson2JsonMessageConverter jsonConverter = new Jackson2JsonMessageConverter();
    jsonConverter.setClassMapper(classMapper());
    return jsonConverter;
}

@Bean
public DefaultClassMapper classMapper() {
    DefaultClassMapper classMapper = new DefaultClassMapper();
    Map> idClassMapping = new HashMap<>();
    idClassMapping.put("thing1", Thing1.class);
    idClassMapping.put("thing2", Thing2.class);
    classMapper.setIdClassMapping(idClassMapping);
    return classMapper;
}

idClassMapping.put(“thing1”, UserInfo.class);

完整配置:

@Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(jsonMessageConverter());
        return rabbitTemplate;
    }
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        Jackson2JsonMessageConverter jsonConverter = new Jackson2JsonMessageConverter();
        jsonConverter.setClassMapper(classMapper());
        return jsonConverter;
    }

    @Bean
    public DefaultClassMapper classMapper() {
        DefaultClassMapper classMapper = new DefaultClassMapper();
        Map> idClassMapping = new HashMap<>();
        idClassMapping.put("thing1", User.class);
        //idClassMapping.put("thing2", Thing2.class);
        classMapper.setIdClassMapping(idClassMapping);
        return classMapper;
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5683502.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存