自学内容网 自学内容网

Java延时队列取消未支付的订单

一、定义延迟任务类

package com.activity.domain;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延迟任务类
 */
public class DelayedCancellation implements Delayed {
    private String order;
    private final long delayTime; // 延迟时间

    public DelayedCancellation(String order, long delayTime) {
        this.order = order;
        this.delayTime = System.currentTimeMillis() + delayTime;
    }

    public String getOrder() {
        return order;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(delayTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        return Long.compare(this.delayTime, ((DelayedCancellation) o).delayTime);
    }
}

二、执行任务

package com.activity.utils;

import java.util.concurrent.DelayQueue;

import com.zaiyun.activity.domain.DelayedCancellation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CancellationManager {
    private static final Logger wechatLogger = LoggerFactory.getLogger("extend-wechat");
    private final DelayQueue<DelayedCancellation> delayQueue = new DelayQueue<>();

    public void scheduleOrderCancellation(String order, long delayTime) {
        DelayedCancellation delayedOrderCancellation = new DelayedCancellation(order, delayTime);
        delayQueue.put(delayedOrderCancellation);
    }

    public void startOrderCancellationScheduler() {
        new Thread(() -> {
            while (true) {
                try {
                    DelayedCancellation delayedOrderCancellation = delayQueue.take();
                    processOrderCancellation(delayedOrderCancellation.getOrder());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }).start();
    }

    /**
     * 执行取消操作
     * @param order
     */
    private void processOrderCancellation(String order) {
        wechatLogger.info("执行取消任务-订单编号:" + order);
    }
}

三、触发使用

/**
     * 30分钟未支付将取消参与
     */
    public static void cancelParticipation(String order) {
        CancellationManager cancellationManager = new CancellationManager();
        cancellationManager.startOrderCancellationScheduler();
        cancellationManager.scheduleOrderCancellation(order, TimeUnit.MINUTES.toMillis(30));
        wechatLogger.info("触发延时队列-订单编号:" + order);
    }

四、执行日志
在这里插入图片描述
本文参考 使用延迟队列处理超时订单


原文地址:https://blog.csdn.net/qq_41688060/article/details/139198469

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!