DelayQueue实现延时消息队列(简易版MQ)

1、需求案例

只要涉及到电商支付相关的订单未支付超时后自动取消订单的操作。我们在开发过程中实现该功能也有很多,例如 消息中间件、定时任务等,每种方法都有各自的优点。这里我使用java DelayQueue容器来实现,优点是本地存储,系统资源消耗低,缺点是单机模式。这种案列还有很多,比如延迟发送消息 考试系统:学生参与考试,不能提前30分钟交卷或者开考前30分钟不能交卷等等。

2、代码实现

1、编写DelayedOrderVo实现类

/**
 * @author Wu_启龙
 * @version 1.0
 * @date 2020/9/4 10:45
 */
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class DelayedOrderVo implements Delayed {

    //设备序列号
    private String orderId;

    //设备下线的过期时间
    private long expire;

    //设备过期时间间隔定义(毫秒),这里方便测试暂时设置为10000毫秒(也就是10秒)
    public static final long expireTime = TimeUnit.MILLISECONDS.toMillis(10000);

    public DelayedOrderVo(String orderId, LocalDateTime serialTime) {
        this.orderId= orderId;
        //转成毫秒
        long creatTime = serialTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        this.expire = expireTime + creatTime;
    }


    /**
     * 获取剩余时间
     *
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(expire - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed other) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - other.getDelay(TimeUnit.MILLISECONDS));
    }
}

2、编写DelayQueue业务类

/**
 * @author Wu_启龙
 * @version 1.0
 * @date 2020/9/4 11:19
 */

@Service
@Slf4j
public class OrderCanelService {
    @Resource
    private OrderService orderService;  //订单增删改查业务逻辑

    //用于存放需要未支付计时订单
    private final static DelayQueue<DelayedOrderVo> delayQueue = new DelayQueue<>();


    //订单取消,数据库改变订单状态,DelayQueue容器移除该订单记录
    public void cancelOrder(String orderNo) {
        //数据库改变订单状态
        orderService.cancelOrder(orderNo);
        //容器遍历找到对应的订单记录,并从容器中移除
        Iterator val = delayQueue.iterator();
        while (val.hasNext()) {
            OrderAutoEntity orderAutoEntity = (OrderAutoEntity) val.next();
            if(orderAutoEntity.getOrderNo().equals(orderNo)){
                delayQueue.remove(orderAutoEntity);
            }
        }
    }

    //往队列中新增订单记录
    public void add(OrderAutoEntity orderAutoEntity) {
        delayQueue.put(orderAutoEntity);
    }

    /**
     * 服务器启动时,自动加载待支付订单
     */
    @PostConstruct
    public void initOrderStatus() {
        log.info(">>>>>>>>>>> 系统启动时,加载所有待支付订单到延时队列 >>>>>>>>>>>>.");
        //未支付订单查询
        QueryWrapper<Order> wrapper = new QueryWrapper();
        wrapper.select("order_no", "create_time").eq("status", "0");
        //获取所有未支付订单,这里用了mybatisplus操作数据库
        List<Map<String, Object>> orders = orderService.listMaps(wrapper);

        //逐个构造Delay的实现类,添加进容器
        for (Map<String, Object> order : orders) {
            Timestamp createTime = (Timestamp) order.get("create_time");
            OrderAutoEntity orderAutoEntity = new OrderAutoEntity((String) order.get("order_no"), createTime.toLocalDateTime());
            delayQueue.add(orderAutoEntity);
        }

        //启动一个线程持续健康订单超时
        Executors.newSingleThreadExecutor().execute(() -> {
            try {
                while (true) {
                    if (delayQueue.size() > 0) {
                        //容器中超时的订单记录会被取出
                        OrderAutoEntity order = delayQueue.take();
                        //修改数据库,容器中移除数据
                        cancelOrder(order.getOrderNo());
                    }
                }
            } catch (InterruptedException e) {
                log.error("InterruptedException error:", e);
            }
        });
    }
}

3、编写订单业务逻辑

需要注意的是:我们前台每次新增订单时,也需要再给容器中添加一条记录。(这里提供一些伪代码,具体的根据自己的业务场景去进行编写)

@RestController
@Slf4j
@RequestMapping("/api")
public class OrderController {
    @Resource
    private OrderCanelService orderCanelService ;
    ...
    //前端页面调用的订单新增接口
    @PostMapping("/order")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity addOrder(@RequestBody Map<String, Object> params) {
        ...
            //构造订单延时类(OrderAutoEntity),这里是伪代码
            OrderAutoEntity orderAutoEntity = new OrderAutoEntity(orderNo, createTime);
            orderAutoService.add(orderAutoEntity);
        ...
    }
    ...
}

总结说明

我这种操作只支持单机情况,一般还可以进一步优化,利用redis:在新增订单时,除了存到数据库,再保留一份到redis中,这样我们在OrderCanelService 的初始化函数initOrderStatus中就不需要查数据库,每次启动就直接读redis中的数据。这里我就没做这么复杂,我们具体的项目中也没用DelayQueue啦,而是用的mq,如果项目中没有使用mq的小伙伴,而正好需要做这个功能的时候呢,则可以参考我这样的写法。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。