当前文章引用连接:springBoot集成Redisson实现延迟队列
**感谢原作者 **
使用场景
1、下单成功,30分钟未支付。支付超时,自动取消订单
2、订单签收,签收后7天未进行评价。订单超时未评价,系统默认好评
3、下单成功,商家5分钟未接单,订单取消
4、配送超时,推送短信提醒…
对于延时比较长的场景、实时性不高的场景,我们可以采用任务调度的方式定时轮询处理。
如:xxl-job。今天我们采用一种比较简单、轻量级的方式,使用 Redis 的延迟队列来进行处理。
当然有更好的解决方案,可根据公司的技术选型和业务体系选择最优方案。
如:使用消息中间件Kafka、RabbitMQ 的延迟队列先不讨论其实现原理,直接实战上代码先实现基于 Redis 的延迟队列
<dependency>
<groupId>org.redissongroupId>
<artifactId>redisson-spring-boot-starterartifactId>
<version>3.10.5version>
dependency>
spring:
redis:
host: 127.0.0.1
port: 6379
password: 123456
database: 12
timeout: 3000
@Slf4j
@Configuration
public class RedissionConfig {
private final String REDISSON_PREFIX = "redis://";
private final RedisProperties redisProperties;
public RedissionConfig(RedisProperties redisProperties) {
this.redisProperties = redisProperties;
}
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
String url = REDISSON_PREFIX + redisProperties.getHost() + ":" + redisProperties.getPort();
config.useSingleServer()
.setAddress(url)
.setPassword(redisProperties.getPassword())
.setDatabase(redisProperties.getDatabase())
.setPingConnectionInterval(2000);
config.setLockWatchdogTimeout(10000L);
try {
return Redisson.create(config);
} catch (Exception e) {
log.error("RedissonClient init redis url:{}, Exception:{}", url, e);
return null;
}
}
}
@Slf4j
@Component
public class RedisDelayQueueUtil {
@Autowired
private RedissonClient redissonClient;
/**
* 添加延迟队列
*
* @param value:队列值
* @param delay:延迟时间
* @param timeUnit:时间单位
* @param queueCode:队列键
* @param
*/
public <T> boolean addDelayQueue(T value, long delay, TimeUnit timeUnit, String queueCode) {
if (StringUtils.isBlank(queueCode) || Objects.isNull(value)) {
return false;
}
try {
// redission的阻塞队列
RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueCode);
// redission的延时队列
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
*/
public <T> T getDelayQueue(@NonNull String queueCode) throws InterruptedException {
if (StringUtils.isBlank(queueCode)) {
return null;
}
RBlockingDeque<Map> blockingDeque = redissonClient.getBlockingDeque(queueCode);
// 将队列中放入的第一个元素取出
T value = (T) blockingDeque.poll();
return value;
}
/**
* 删除指定队列中的消息
* @param o 指定删除的消息对象队列值(同队列需保证唯一性)
* @param queueCode 指定队列键
*/
public boolean removeDelayedQueue(Object o,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();
if(flag){
log.info("删除延时队列成功, 删除信息:{},延迟时间:{}", o,queueCode);
}
return flag;
}
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum RedisDelayQueueEnum {
ORDER_PAYMENT_TIMEOUT("ORDER_PAYMENT_TIMEOUT","支付超时,自动取消订单", "orderPaymentTimeout");
/**
* 延迟队列 Redis Key
*/
private String code;
/**
* 描述
*/
private String name;
/**
* 延迟队列具体业务实现的 Bean
* 可通过 Spring 的上下文获取
*/
private String beanId;
}
/**
* @ClassName: RedisDelayQueueHandle
* @Desc: 延迟队列执行器
* @Author:
* @Date: 2022/10/19 21:27
**/
public interface RedisDelayQueueHandle<T> {
void execute(T t);
}
/**
* @ClassName: OrderPaymentTimeout
* @Desc: 订单支付超时处理
* @Author:
* @Date: 2022/10/19 21:28
**/
@Component
@Slf4j
public class OrderPaymentTimeout implements RedisDelayQueueHandle<Map> {
@Override
public void execute(Map map) {
log.info("订单支付超时延迟消息:{}", map);
// TODO 订单支付超时,自动取消订单处理业务...
}
}
/**
* SpringUtil
* Created by LPB on 2021/04/20.
*/
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringUtil.context = context;
}
public static <T> T getBean(Class<T> clazz) {
if (clazz == null) {
return null;
}
return context.getBean(clazz);
}
public static <T> T getBean(String beanId) {
if (beanId == null) {
return null;
}
return (T) context.getBean(beanId);
}
public static ApplicationContext getContext() {
if (context == null) {
return null;
}
return context;
}
}
/**
* 启动延迟队列
* Created by LPB on 2021/04/20.
*/
@Slf4j
@Component
public class RedisDelayQueueRunner implements CommandLineRunner {
@Autowired
private RedisDelayQueueUtil redisDelayQueueUtil;
/**
* RedisDelayQueueRunner 下的 ThreadPoolTaskExecutor
*/
@Autowired(required = false)
private ThreadPoolTaskExecutor ptask;
@Override
public void run(String... args) {
ptask.execute(() -> {
while (true) {
try {
RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values();
for (RedisDelayQueueEnum queueEnum : queueEnums) {
Object value = redisDelayQueueUtil.getDelayQueue(queueEnum.getCode());
if (value != null) {
RedisDelayQueueHandle<Object> redisDelayQueueHandle = SpringUtil.getBean(queueEnum.getBeanId());
redisDelayQueueHandle.execute(value);
}
}
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
log.error("Redission延迟队列监测异常中断):{}", e.getMessage());
}
}
});
log.info("Redission延迟队列监测启动成功");
}
}
PS:因为 redisson 启动后会订阅一个 key 监听一个阻塞队列,如果一个 key 列表没有元素就会阻塞,直到有超时元素或发现有可弹出元素为止;
然而现实业务中会存在多种延迟场景,如上面使用了业务枚举,会有多个 key,所以消费线程中为每个业务枚举 key 分配自己独立的线程;
防止多个业务 key 用一个线程,当 key 1 没有元素时,redisson 获取元素发生阻塞,而 key 2 有元素过期时因线程阻塞而导致 key 2 业务元素一直未消费。
以上步骤,Redis 延迟队列核心代码已经完成,下面我们写一个测试接口,用 PostMan 模拟测试一下
/**
* 延迟队列测试
* Created by LPB on 2020/04/20.
*/
@RestController
public class RedisDelayQueueController {
/**
* 获取redis 延时工具类
*/
private final RedisDelayQueueUtil redisDelayQueueUtil = SpringUtils.getBean(RedisDelayQueueUtil.class);
@GetMapping(value = "/addQueue")
public AjaxResult placeOrder() {
System.out.println("模拟下单处理完成");
Map<String, String> map1 = new HashMap<>();
map1.put("orderId", "100");
map1.put("remark", "支付超时,自动取消订单");
// 添加订单支付超时,自动取消订单延迟队列。延迟40秒钟取消订单
boolean b = redisDelayQueueUtil.addDelayQueue(map1, 40, TimeUnit.SECONDS, RedisDelayQueueEnum.ORDER_PAYMENT_TIMEOUT.getCode());
return AjaxResult.success(b);
}
}