SpringBoot+rabbitMq实现定时关闭订单

文章目录

    • springBoot+rabbitMq实现定时关闭订单
      • pom导入依赖
      • 配置文件 添加rabbitMq的配置
      • 添加队列、交换机配置枚举类
      • 添加rabbitMq配置文件--RabbitMqConfig
      • 添加消息的生产者类--CancelOrderSender
      • 添加消息的消费者类-CancelOrderReceiver
      • 添加订单相关的接口类-OmsPortalOrderService
      • 添加订单相关的接口实现类-OmsPortalOrderServiceImpl
      • 添加订单操作类控制器--OmsPortalOrderController
      • 使用postman测试-生成订单,去rabbit管理后台查看队列是否有消息并且能否正常消费。

springBoot+rabbitMq实现定时关闭订单

参考Mall商城,小伙伴们可以去看mall的官方文档。

pom导入依赖

 <!--消息队列相关依赖-->
 <dependency>  
 <groupId>org.springframework.boot</groupId>  
 <artifactId>spring-boot-starter-amqp</artifactId>
 </dependency>

配置文件 添加rabbitMq的配置

spring:
rabbitmq:
host: 安装rabbitMq服务的Ip # rabbitmq的连接地址
port: 5672 # rabbitmq的连接端口号
virtual-host: /mall # rabbitmq的virtual-host 默认/,需要去rabbitmq后台管理平台添加。
username: mall
password: 123456
publisher-returns: false #开启返回模式(true为开启确认回调)
publisher-confirm-type: none #应答模式(true为开启应答模式)

添加队列、交换机配置枚举类

package com.dwbjava.DwbApp.Config.RabbitMq;

import lombok.Getter;

/**
 * 消息队列枚举配置
 */
@Getter
public enum QueueEnum {
    /**
     * 商城订单消息通知队列
     */
    QUEUE_ORDER_CANCEL("mall.order.direct","mall.order.cancel","mall.order.cancel"),
    /**
     * 商城订单消息通知ttl队列
     */
    QUEUE_TTL_ORDER_CANCLE("mall.order.direct.ttl","mall.order.cancel.ttl","mall.order.cancel.ttl");

    /**
     * 交换机名称
     */
    private String exchange;
    /**
     * 队列名称
     */
    private  String name;
    /**
     * 路由键
     */
    private String routeKey;

    QueueEnum(String exchange, String name, String routeKey) {
        this.exchange=exchange;
        this.name=name;
        this.routeKey=routeKey;
    }
    
}

添加rabbitMq配置文件–RabbitMqConfig

package com.dwbjava.DwbApp.Config.RabbitMq;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;


/**
 * rabbitmq消息队列配置
 */
@Configuration
public class RabbitMqConfig {

    /**
     * 订单消息实际消费队列所绑定的交换机
     * @return
     */
    @Bean
    DirectExchange orderDirect(){
        return (DirectExchange) ExchangeBuilder
                .directExchange(QueueEnum.QUEUE_ORDER_CANCEL.getExchange())
                .durable(true)
                .build();
    }
    
    /**
     * 订单消息实际消费队列
     * @return
     */
    @Bean
    public Queue orderQueue(){
        return  new Queue(QueueEnum.QUEUE_ORDER_CANCEL.getName(),true,false,false);
    }

    /**
     * 订单延迟队列(死信队列)
     * @return
     */
    @Bean
    public Queue orderTtlQueue(){
        Map<String,Object> args=new HashMap<>();
//        args.put("x-message-ttl",3000);
        args.put("x-dead-letter-exchange",QueueEnum.QUEUE_ORDER_CANCEL.getExchange());
        args.put("x-dead-letter-routing-key",QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey());
       return  new Queue(QueueEnum.QUEUE_TTL_ORDER_CANCLE.getName(),true,false,false,args);
    }

    /**
     * 队列绑定交换机
     * @return
     */
    @Bean
    Binding orderBinding(){
        return BindingBuilder
                .bind(orderQueue())
                .to(orderDirect())
                .with(QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey());
    }
}

添加消息的生产者类–CancelOrderSender

package com.dwbjava.DwbApp.Service.RabbitMqService;

import com.dwbjava.DwbApp.Config.RabbitMq.QueueEnum;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 取消订单消息的发出者
 */
@Component
public class CancelOrderSender {
    @Autowired
    AmqpTemplate amqpTemplate;

    public void  sendMessage(Long orderId,final long delayTimes){
        System.out.println("给队列发送消息,Id是"+orderId);
        MessagePostProcessor message=new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration(delayTimes+"");
                return message;
            }
        };
        //给延时队列发送消息
        amqpTemplate.convertAndSend(QueueEnum.QUEUE_TTL_ORDER_CANCLE.getName(),(Object)orderId,message);
    }
    
}

添加消息的消费者类-CancelOrderReceiver

package com.dwbjava.DwbApp.Service.RabbitMqService;

import com.dwbjava.DwbApp.Service.workOrder.OmsPortalOrderService;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component

public class CancelOrderReceiver {
    @Autowired
    OmsPortalOrderService omsPortalOrderService;

    //@RabbitHandler
    @RabbitListener(queues="mall.order.cancel")
    public void handler(String msg){
        System.out.println("监听到要被删除的订单Id"+msg);
        //omsPortalOrderService.cancelOrder(msg);
    }

}

添加订单相关的接口类-OmsPortalOrderService

package com.dwbjava.DwbApp.Service.workOrder;

/**
 * 前台订单管理Service
 */
public interface OmsPortalOrderService {
    /**
     * 生成订单
     * @param orderId
     * @return
     */
    int generateOrder(Long orderId);

    /**
     * 取消单个超时订单
     * @param orderId
     */
    void cancelOrder(Long orderId);
}

添加订单相关的接口实现类-OmsPortalOrderServiceImpl

package com.dwbjava.DwbApp.Service.workOrder.Impl;

import com.dwbjava.DwbApp.Service.RabbitMqService.CancelOrderSender;
import com.dwbjava.DwbApp.Service.workOrder.OmsPortalOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OmsPortalOrderServiceImpl  implements OmsPortalOrderService {
    @Autowired
    private CancelOrderSender cancelOrderSender;

    /**
     * 生成订单
     * @param orderId
     * @return
     */
    @Override
    public int generateOrder(Long orderId) {
        System.out.println("生成订单订单Id"+orderId);
        //下单完成后开启一个延迟消息
        sendDelayMessage(orderId);
        return 0;
    }

    /**
     * 取消单个超时订单
     *
     * @param orderId
     */
    @Override
    public void cancelOrder(Long orderId) {
        System.out.println("我要取消这个订单了,订单Id是"+orderId);
    }

    private  void  sendDelayMessage(Long orderId){
        //获取订单超时时间,假设为60分钟
        long delayTimes=20*1000;
        //发生延迟消息
        cancelOrderSender.sendMessage(orderId,delayTimes);
    }
    
}

添加订单操作类控制器–OmsPortalOrderController

package com.dwbjava.DwbApp.Controller.WorkOrder;

import com.dwbjava.DwbApp.Dto.WorkOrderDto.OmsPortalOrderDto.OmsPortalOrderAddDto;
import com.dwbjava.DwbApp.Service.workOrder.OmsPortalOrderService;
import com.dwbjava.DwbApp.Util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/OmsPortalOrder")
public class OmsPortalOrderController {
    @Autowired
    OmsPortalOrderService omsPortalOrderService;

    /**
     * 生成订单
     * @param omsPortalOrderAddDto
     * @return
     */
    @RequestMapping("/generateOrder")
    public ResultUtil generateOrder(@RequestBody OmsPortalOrderAddDto omsPortalOrderAddDto){
        omsPortalOrderService.generateOrder(omsPortalOrderAddDto.getOrderId());
        return  new ResultUtil();
    }
}

使用postman测试-生成订单,去rabbit管理后台查看队列是否有消息并且能否正常消费。

SpringBoot+rabbitMq实现定时关闭订单_第1张图片


SpringBoot+rabbitMq实现定时关闭订单_第2张图片

你可能感兴趣的:(SpringBoot)