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; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)