1. 默认转换器
@Test
public void testSendMap() throws InterruptedException {// 准备消息Map<String, Object> msg = new HashMap<>();msg.put("name", "harry");msg.put("age", 21);// 发送消息rabbitTemplate.convertAndSend("object.queue", msg);
}
2. 配置转换器
引入依赖
<!--如果项目中引入了spring-boot-starter-web依赖,则无需再次引入-->Jackson依赖。
<dependency><groupId>com.fasterxml.jackson.dataformat</groupId><artifactId>jackson-dataformat-xml</artifactId><version>2.9.10</version>
</dependency>
@Bean
public MessageConverter messageConverter(){// 1.定义消息转换器Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter();// 2.配置自动创建消息id,用于识别不同消息,也可以在业务中基于ID判断是否是重复消息jackson2JsonMessageConverter.setCreateMessageIds(true);return jackson2JsonMessageConverter;
}
3. 消费消息
@RabbitListener(queues = "object.queue")
public void listenSimpleQueueMessage(Map<String, Object> msg) {System.out.println("消费者接收到object.queue消息:【" + msg + "】");
}