redisson延迟队列实现倒计时

d_hero
发布于 2023-7-3 11:56
浏览
0收藏

了解老王的,都知道我不喜欢废话直接代码

pom.xml

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.13.4</version>
</dependency>

代码结构

redisson延迟队列实现倒计时-鸿蒙开发者社区

RedisDelayQueueEnum- 延迟队列业务枚举,定义倒计时任务的队列

RedisDelayQueueHandle - 延迟队列执行器顶级接口

OrderNotEvaluatedTimeout - 订单超时未评价处理实现类

OrderPaymentTimeout - 订单支付超时处理实现类

RedisDelayQueueStarter - 启动延迟队列监测扫描器

RedisDelayQueueUtil - 分布式延时队列工具类

RedisDelayQueueController - 测试类

RedisDelayQueueEnum

package com.boot.redisson.delayQueue.constant;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;


/**
 * 描述: 延迟队列业务枚举 <br>
 * 作者: IT学习道场 <br>
 * 时间: 2022/8/05 14:16
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum RedisDelayQueueEnum {

    orderPaymentTimeout("orderPaymentTimeout","订单支付超时,自动取消订单", "orderPaymentTimeout"),
    orderNotEvaluatedTimeout("orderNotEvaluatedTimeout", "订单超时未评价,系统默认好评", "orderNotEvaluatedTimeout");
 
    /**
     * 延迟队列 Redis Key
     */
    private String code;
 
    /**
     * 中文描述
     */
    private String name;
 
    /**
     * 延迟队列具体业务实现的 Bean
     * 可通过 Spring 的上下文获取
     */
    private String beanId;
 
}

RedisDelayQueueHandle

package com.boot.redisson.delayQueue.handler;


/**
 * 描述: 延迟队列执行器 <br>
 * 作者: IT学习道场 <br>
 * 时间: 2022/8/05 14:16
 */
public interface RedisDelayQueueHandle<T> {
 
    void execute(T t);
 
}

OrderNotEvaluatedTimeout

package com.boot.redisson.delayQueue.handler.impl;

import com.boot.redisson.delayQueue.handler.RedisDelayQueueHandle;
import com.boot.redisson.model.Comment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * 描述: 订单超时未评价处理类 <br>
 * 作者: IT学习道场<br>
 * 时间: 2022/8/05 14:16
 */
@Component
@Slf4j
public class OrderNotEvaluatedTimeout implements RedisDelayQueueHandle<Comment> {
    @Override
    public void execute(Comment comment) {
        log.info("(收到订单超时未评价延迟消息) {}", comment);
        // TODO 订单超时未评价,系统默认好评处理业务...
 
    }
}

OrderPaymentTimeout

package com.boot.redisson.delayQueue.handler.impl;

import com.boot.redisson.delayQueue.handler.RedisDelayQueueHandle;
import com.boot.redisson.model.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * 描述: 订单支付超时处理类 <br>
 * 作者: IT学习道场 <br>
 * 时间: 2022/8/05 14:16
 */
@Component
@Slf4j
public class OrderPaymentTimeout implements RedisDelayQueueHandle<Order> {
    @Override
    public void execute(Order order) {
        log.info("(收到订单支付超时延迟消息) {}", order);
        // TODO 订单支付超时,自动取消订单处理业务...
    }
}

RedisDelayQueueStarter

package com.boot.redisson.delayQueue.starter;


import com.boot.redisson.delayQueue.constant.RedisDelayQueueEnum;
import com.boot.redisson.delayQueue.handler.RedisDelayQueueHandle;
import com.boot.redisson.delayQueue.util.RedisDelayQueueUtil;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述: 启动延迟队列监测扫描 <br>
 * 作者: IT学习道场 <br>
 * 时间: 2022/8/05 16:16
 */
@Slf4j
@Component
public class RedisDelayQueueStarter{
    @Autowired
    private RedisDelayQueueUtil redisDelayQueueUtil;
    @Autowired
    private ApplicationContext context;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    private final long period = 500L;

    /**
     * 线程池,维护keyAliveTime
     */
    private static final ScheduledExecutorService SCHEDULER = new ScheduledThreadPoolExecutor(1,
            new ThreadFactoryBuilder().setNameFormat("queue-delay-%d").setDaemon(true).build());

    @PostConstruct
    public void run(){

        // 每秒执行一次「续时」操作
        SCHEDULER.scheduleAtFixedRate(() -> {
            RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values();
            for (RedisDelayQueueEnum queueEnum : queueEnums) {
                Object value = redisDelayQueueUtil.getDelayQueue(queueEnum.getCode());
                if (value != null) {
                    RedisDelayQueueHandle<Object> redisDelayQueueHandle = (RedisDelayQueueHandle<Object>)context.getBean(queueEnum.getBeanId());
                    taskExecutor.execute(() -> {redisDelayQueueHandle.execute(value);});
                    //redisDelayQueueHandle.execute(value);
                }
            }

        }, 0, period, TimeUnit.MILLISECONDS);

        log.info("====================Redission延迟队列监测启动成功====================");

    }
}

RedisDelayQueueUtil

package com.boot.redisson.delayQueue.util;

import io.micrometer.core.instrument.util.StringUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 描述: 分布式延时队列工具类 <br>
 * 作者: IT学习道场 <br>
 * 时间: 2022/8/05 14:16
 */
@Slf4j
@Component
public class RedisDelayQueueUtil {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 添加延迟队列
     *
     * @param value     队列值
     * @param delay     延迟时间
     * @param timeUnit  时间单位
     * @param queueCode 队列键
     * @param <T>
     */
    public <T> boolean addDelayQueue(@NonNull T value, @NonNull long delay, @NonNull TimeUnit timeUnit, @NonNull String queueCode) {
        if (StringUtils.isBlank(queueCode) || Objects.isNull(value)) {
            return false;
        }
        try {
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueCode);
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            delayedQueue.offer(value, delay, timeUnit);
            //delayedQueue.destroy();
            log.info("(添加延时队列成功) 队列键:{},队列值:{},延迟时间:{}", queueCode, value, timeUnit.toSeconds(delay) + "秒");
        } catch (Exception e) {
            log.error("(添加延时队列失败) {}", e.getMessage());
            throw new RuntimeException("(添加延时队列失败)");
        }
        return true;
    }

    /**
     * 获取延迟队列
     *
     * @param queueCode
     * @param <T>
     */
    public <T> T getDelayQueue(@NonNull String queueCode) {
        if (StringUtils.isBlank(queueCode)) {
            return null;
        }
        RBlockingDeque<Objects> blockingDeque = redissonClient.getBlockingDeque(queueCode);
        RDelayedQueue<Objects> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
        T value = (T) blockingDeque.poll();
        return value; 
    } 
    /** 
     * 删除指定队列中的消息 
     * 
     * @param o 指定删除的消息对象队列值(同队列需保证唯一性) 
     * @param queueCode 指定队列键 
     */ 
     public boolean removeDelayedQueue(@NonNull Object o, @NonNull String queueCode) { 
        if (StringUtils.isBlank(queueCode) || Objects.isNull(o)) { 
            return false; 
        } 
        RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueCode); RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque); boolean flag = delayedQueue.remove(o); 
        //delayedQueue.destroy(); 
        return flag; 
    } 
}

RedisDelayQueueController 测试下

package com.boot.redisson.delayQueue.controller;

import com.boot.redisson.delayQueue.constant.RedisDelayQueueEnum;
import com.boot.redisson.delayQueue.util.RedisDelayQueueUtil;
import com.boot.redisson.model.Comment;
import com.boot.redisson.model.Order;
import com.boot.redisson.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


/**
 * 描述: 延迟队列测试 <br>
 * 作者: IT学习道场 <br>
 * 时间: 2022/8/05 14:16
 */
@RequestMapping("/redisDelayQueue")
@RestController
public class RedisDelayQueueController {
 
    @Autowired
    private RedisDelayQueueUtil redisDelayQueueUtil;
 
    @PostMapping("/addQueue")
    public void addQueue() throws ClassNotFoundException {

        Order order1 = new Order(1, "订单支付1超时,自动取消订单");
        Order order2 = new Order(2, "订单支付2超时,自动取消订单");
        Order order3 = new Order(3, "订单支付3超时,自动取消订单");
        String string = "{\"orderId\": 5,\"remark\": \"短发女生的烦恼\"}";
        Class<?> clazz = Class.forName("com.boot.redisson.model.Order");
        Object object = JsonUtil.json2Object(string, clazz);

        Comment comment = new Comment(4, "订单超时未评价,系统默认好评");

        // 添加订单支付超时,自动取消订单延迟队列。为了测试效果,延迟10秒钟
        redisDelayQueueUtil.addDelayQueue(order1, 10, TimeUnit.SECONDS, RedisDelayQueueEnum.orderPaymentTimeout.getCode());

        // 添加订单支付超时,自动取消订单延迟队列。为了测试效果,延迟10秒钟
        redisDelayQueueUtil.addDelayQueue(order2, 10, TimeUnit.SECONDS, RedisDelayQueueEnum.orderPaymentTimeout.getCode());


        // 添加订单支付超时,自动取消订单延迟队列。为了测试效果,延迟10秒钟
        redisDelayQueueUtil.addDelayQueue(order3, 30, TimeUnit.SECONDS, RedisDelayQueueEnum.orderPaymentTimeout.getCode());

        // 添加订单支付超时,自动取消订单延迟队列。为了测试效果,延迟10秒钟
        redisDelayQueueUtil.addDelayQueue(object, 40, TimeUnit.SECONDS, RedisDelayQueueEnum.orderPaymentTimeout.getCode());



        // 订单超时未评价,系统默认好评。为了测试效果,延迟20秒钟
        redisDelayQueueUtil.addDelayQueue(comment, 50, TimeUnit.SECONDS, RedisDelayQueueEnum.orderNotEvaluatedTimeout.getCode());
    }
 
}

完事,去玩玩吧




文章转载自公众号:IT学习道场

分类
标签
已于2023-7-3 11:56:02修改
收藏
回复
举报
回复
    相关推荐