如何使用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;
 
}

执行器

在这里插入图片描述

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延迟队列启动成功)");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值