发送时需要将对象序列化为json字符串,接收时反序列化为对象。
1、序列化 在任意配置类下提供RabbitTemplate的bean,覆盖Springboot的自动化配置。将消息转译器设置为springboot提供的Jackson转译器。
// 提供自定义RabbitTemplate,将对象序列化为json串 @Bean public RabbitTemplate jacksonRabbitTemplate(ConnectionFactory connectionFactory) { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter()); return rabbitTemplate; }2、反序列化 实现RabbitListenerConfigurer接口,配置反序列化转译器(可以将序列化转译器的bean也放在这里面)
@Configuration public class RabbitMQConfig implements RabbitListenerConfigurer { // 可以将json串反序列化为对象 @Override public void configureRabbitListeners(RabbitListenerEndpointRegistrar rabbitListenerEndpointRegistrar) { rabbitListenerEndpointRegistrar.setMessageHandlerMethodFactory(messageHandlerMethodFactory()); } @Bean MessageHandlerMethodFactory messageHandlerMethodFactory(){ DefaultMessageHandlerMethodFactory messageHandlerMethodFactory = new DefaultMessageHandlerMethodFactory(); messageHandlerMethodFactory.setMessageConverter(mappingJackson2MessageConverter()); return messageHandlerMethodFactory; } @Bean public MappingJackson2MessageConverter mappingJackson2MessageConverter(){ return new MappingJackson2MessageConverter(); } // 提供自定义RabbitTemplate,将对象序列化为json串 @Bean public RabbitTemplate jacksonRabbitTemplate(ConnectionFactory connectionFactory) { RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter()); return rabbitTemplate; } }即可定义消费者直接以对象的形式接收消息
@RabbitListener(queues = "huawei") public void huaweiHandler(SysUserEntity msg) { System.out.println("huaweiHandler>>>>>" + msg); }生产者直接发送对象
SysUserEntity user = new SysUserEntity(1l,"wtq","123",new Date()); rabbitTemplate.convertAndSend(RabbitTopicConfig.TOPIC_NAME, "huawei.",user);发送后消费者消费消息成功,控制台打印