供應商后臺-點擊發貨-默認3天自動收貨確認,更新訂單狀態已完成。
1 pom.xml 引入依賴:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency>
2 運營后臺-訂單-發貨按鈕:生產者發布延時消息
// 5. 發送自動確認收貨消息// 計算延遲時間String autoDeliveryDays = configService.getConfigVal(SettingsEnum.AUTO_DELIVERY_DAYS);if (StrUtil.isNotBlank(autoDeliveryDays)) {// long delayTime = Long.parseLong(autoDeliveryDays) * 24 * 60 * 60 * 1000;BigDecimal delayTime = new BigDecimal(autoDeliveryDays).multiply(new BigDecimal(24 * 60 * 60 * 1000));rabbitTemplate.convertAndSend(RabbitMQConfig.DELAY_EXCHANGE,RabbitMQConfig.ORDER_CONFIRM_RECEIPT_ROUTING_KEY,order.getOrderId(),message -> {message.getMessageProperties().setHeader("x-delay", delayTime.longValue());return message;});}
3 RabbitMQ消息隊列,路由鍵,交換機配置
package com.tigshop.common.config;import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;@Configuration
public class RabbitMQConfig { // 路由鍵public static final String ORDER_CONFIRM_RECEIPT_ROUTING_KEY = "order.confirm.receipt.routing.key";// 隊列名稱public static final String ORDER_CONFIRM_RECEIPT_QUEUE = "orderConfirmReceiptQueue";/*** 直連交換機(普通交換機)*/@Beanpublic DirectExchange directExchange() {return new DirectExchange(DIRECT_EXCHANGE);}/*** 延遲交換機*/@Beanpublic CustomExchange delayExchange() {Map<String, Object> args = new HashMap<>();args.put("x-delayed-type", "direct");return new CustomExchange(DELAY_EXCHANGE, "x-delayed-message", true, false, args);}@Beanpublic Queue orderConfirmReceiptQueue() {return QueueBuilder.durable(ORDER_CONFIRM_RECEIPT_QUEUE).build();}@Beanpublic Binding orderConfirmReceiptBinding() {return BindingBuilder.bind(orderConfirmReceiptQueue()).to(delayExchange()).with(ORDER_CONFIRM_RECEIPT_ROUTING_KEY).noargs();}}
4 消費者實現監聽器消費
@RequiredArgsConstructor
@Service
@Slf4j
public class RabbitMqConsumer{@RabbitListener(queues = RabbitMQConfig.ORDER_CONFIRM_RECEIPT_QUEUE)public void receiveOrderConfirmReceiptMessage(Integer orderId) {log.info("收到訂單自動確認收貨消息:{}", orderId);// 判斷是否已經收貨Long receivedCount = orderService.lambdaQuery().eq(Order::getOrderId, orderId).eq(Order::getShippingStatus, ShippingStatusEnum.SHIPPED.getCode()).count();if (receivedCount == 1) {return;}// 判斷訂單是否售后中Long aftersalesCount = aftersalesService.lambdaQuery().eq(Aftersales::getOrderId, orderId).eq(Aftersales::getStatus, AftersalesStatusEnum.IN_REVIEW.getCode()).count();if (aftersalesCount == 1) {return;}try {orderService.confirmReceipt(orderId);} catch (GlobalException e) {log.error("【異常】收到訂單自動確認收貨消息 RabbitMQ:{}", e.getMessage());}}
}