Rabbit发送消息,消费者消费异常
背景:
在步骤1下创建订单,步骤2下提交消息
@Transactional
public void tradeHandler(Map map) {
// 1.生成统一订单
var unifyOrder = orderService.create(orderService.getUnifyOrderDTO(fee, alipayOrder));
//2.充值通知+首充赠送礼
rabbitTemplate.convertAndSend(ChargeQueueConfig.EXCHANGE_NAME, ChargeQueueConfig.QUEUE_NAME, unifyOrder.getId());
}
原因:事务导致数据未提交,消费者监听到消息,使用订单ID查询订单失败
解决:直接提交unifyOrder对象,消费者直接使用创建的order
(注意:如果在received 中还像第一版直接转自定义对象,消息进程会报错)
解决方案是使用Jackson2JsonMessageConverter 。在发送消息时,它会先将自定义的消息类序列化成json格式,再转成byte构造 Message
//发送 设置Converter
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setMessageConverter(new Jackson2JsonMessageConverter());
return template;
}
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setMessageConverter(new Jackson2JsonMessageConverter());
return factory;
}
//消费时 指定Converter
@RabbitListener(bindings = {
@QueueBinding(value = @Queue(value = "queue-order"),
exchange = @Exchange(value = "exchange-order"),
key = "rkey-order")},containerFactory="rabbitListenerContainerFactory")
参考:https://www.cnblogs.com/timseng/p/11688019.html