- 生产者完成创建订单和扣减库存之后,发送消息到延迟队列。
cartClient.deleteCartItemByIds(itemIds);try {itemClient.deductStock(detailDTOS);} catch (Exception e) {throw new RuntimeException("库存不足!");}rabbitTemplate.convertAndSend(MQConstants.DELAY_EXCHANGE_NAME,MQConstants.DELAY_ORDER_KEY,order.getId(),message -> {message.getMessageProperties().setDelay(10000);return message;});
- 消费者监听消息,先查订单状态,没支付在查支付信息。
@Slf4j
@Component
@AllArgsConstructor
public class OrderDelayMessageListener {private final IOrderService orderService;private final PayClient payClient;@RabbitListener(bindings = @QueueBinding(value = @Queue(name = MQConstants.DELAY_ORDER_QUEUE_NAME),exchange = @Exchange(name = MQConstants.DELAY_EXCHANGE_NAME, delayed = "true"),key = MQConstants.DELAY_ORDER_KEY))public void listenOrderDelayMessage(Long orderId) {Order order = orderService.getById(orderId);if(order == null || order.getStatus()!=1) {log.info("delayMQ:用户已支付订单【{}】",orderId);return;}PayOrderDTO payOrder = payClient.queryPayOrderByBizOrderNo(orderId);if (payOrder == null || payOrder.getStatus() == 3) {orderService.markOrderPaySuccess(orderId);log.info("delayMQ:已更新订单【{}】",orderId);} else {orderService.cancelOrder(orderId);log.info("delayMQ:已取消订单【{}】",orderId);}}
}