文章目录

  • 准备
  • redis延迟队列工具类
  • 枚举
  • 执行器
  • 开搞
  • 发送延迟队列
  • 线程池接受队列处理业务


准备

redis延迟队列工具类

redis线程池 redisson 线程池_redis

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.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class RedisDelayQueueUtil {
 
    @Autowired
    private RedissonClient redissonClient;
 
    /**
     * 添加延迟队列
     * @param value 队列值
     * @param delay 延迟时间
     * @param timeUnit 时间单位
     * @param queueCode 队列键
     * @param <T>
     */
    public <T> void addDelayQueue(T value, long delay, TimeUnit timeUnit, String queueCode){
        try {
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueCode);
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            delayedQueue.offer(value, delay, timeUnit);
            log.info("(添加延时队列成功) 队列键:{},队列值:{},延迟时间:{}", queueCode, value, timeUnit.toHours(delay) + "小时");
        } catch (Exception e) {
            log.error("(添加延时队列失败) {}", e.getMessage());
            throw new RuntimeException("(添加延时队列失败)");
        }
    }
 
 /**
  * 获取延迟队列
  * @param queueCode
  * @param <T>
  * @return
  * @throws InterruptedException
  */
    public <T> T getDelayQueue(String queueCode) throws InterruptedException {
         RBlockingDeque<Map> blockingDeque = redissonClient.getBlockingDeque(queueCode);
        if (blockingDeque.size() > 0) {
            T value = (T) blockingDeque.take();
            return value;
        }
        return null;
 }
}

枚举

@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum RedisDelayQueueEnum {
 
 ORDER_PAYMENT_TIMEOUT("ORDER_PAYMENT_TIMEOUT","订单支付超时,自动取消订单", "orderTimeout");

 /**
  * 延迟队列 Redis Key
  */
 private String code;
 
 /**
  * 中文描述
  */
 private String name;
 
 /**
  * 延迟队列具体业务实现的 Bean
  * 可通过 Spring 的上下文获取
  */
 private String beanId;
 
}

执行器

redis线程池 redisson 线程池_java_02

public interface RedisDelayQueueHandle<T> {
 
 void execute(T t);
 
}
  • 这里是一个bean,名字默认是驼峰命名,便于线程池部分获取到此bean用于处理执行
@Component
@Slf4j
public class OrderTimeout implements RedisDelayQueueHandle<String> {

    @Autowired
    private ActActivityTravelOrderService orderService;
    @Autowired
    private ActActivityService actActivityService;
    @Override
    public void execute(String id) {
        log.info("(收到订单超时延迟消息) {}", id);
        ActActivityTravelOrder order = orderService.getById(id);
        //超时未确认,出行机构未提交方案
        if (Objects.isNull(order.getSchemeId())){
            String activityId = order.getActivityId();
            ActActivity activity = actActivityService.getById(activityId);
            LambdaUpdateWrapper<ActActivity> lambdaUpdate = Wrappers.lambdaUpdate();
            lambdaUpdate.set(ActActivity::getTravelAgencyId, null)
                        .set(ActActivity::getTravelStatus, ActivityTravelStatus.NO_SELECT)
                        .eq(ActActivity::getId, activity.getId());
            actActivityService.update(lambdaUpdate);
        }
    }
}

开搞

发送延迟队列

  • 用于实际业务场景中
redisDelayQueueUtil.addDelayQueue(travelOrder.getId(), 4, TimeUnit.HOURS, RedisDelayQueueEnum.ORDER_PAYMENT_TIMEOUT.getCode());

线程池接受队列处理业务

import com.xk.practice.act.emuns.RedisDelayQueueEnum;
import com.xk.practice.act.handler.RedisDelayQueueHandle;
import com.xk.practice.act.utils.RedisDelayQueueUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.xk.base.core.util.SpringContextHolder;

import java.util.concurrent.Executors;
@Slf4j
@Component
public class RedisDelayQueueRunner implements CommandLineRunner {

    @Autowired
    private RedisDelayQueueUtil redisDelayQueueUtil;

    @Override
    public void run(String... args) {
        Executors.newFixedThreadPool(1).execute(() -> {
            while (true) {
                try {
                    RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values();
                    for (RedisDelayQueueEnum queueEnum : queueEnums) {
                        Object value = redisDelayQueueUtil.getDelayQueue(queueEnum.getCode());
                        if (value != null) {
                            RedisDelayQueueHandle redisDelayQueueHandle = SpringContextHolder.getBean(queueEnum.getBeanId());
                            redisDelayQueueHandle.execute(value);
                        }
                    }
                } catch (Exception e) {
                    log.error("(Redis延迟队列异常中断) {}", e.getMessage());
                }
            }
        });
        log.info("(Redis延迟队列启动成功)");
    }
}