Redisson实现延迟队列

延迟队列是指在队列中存储带有过期时间的数据,在过期时间到达时自动从队列中移除。

延时队列的使用场景:

  • 订单超过15分钟未支付自动取消
  • 推送数据至第三方平台,如果失败重新入队推送,推送间隔时间随着失败次数增加而扩大。
  • 分布式情况下一个定时任务往队列内推,多个实例同时处理任务。

Redisson实现的延迟队列是基于Redis的zset命令实现的,通过将数据存储到zset中,并设置过期时间作为score,通过定时任务轮询zset来实现延迟队列的功能。

以下提供一个 RedisDelayQueueUtil 来简化操作。

java 复制代码
@Slf4j
@Component
public class RedisDelayQueueUtil implements ApplicationContextAware {

    private static RedissonClient redissonClient;

    /**
     * 添加延迟队列
     * @param value 队列值
     * @param delay 延迟时间
     * @param timeUnit 时间单位
     * @param queueCode 队列键
     * @param <T>
     */
    public static <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("Redisson添加延时队列成功 队列键:{},队列值:{},延迟时间:{}", queueCode, value, timeUnit.toSeconds(delay) + "秒");
        } catch (Exception e) {
            log.error("Redisson添加延时队列失败 {}", e.getMessage());
            throw new RuntimeException("Redisson添加延时队列失败");
        }
    }

    /**
     * 获取延迟队列 - 会阻塞
     * @param queueCode 队列名称
     * @return  <T> 数据
     * @throws InterruptedException
     */
    public static <T> T getDelayQueue(String queueCode) throws InterruptedException {
        RBlockingDeque<T> blockingDeque = redissonClient.getBlockingDeque(queueCode);
        return blockingDeque.take();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RedisDelayQueueUtil.redissonClient = applicationContext.getBean(RedissonClient.class);
    }
}
相关推荐
lisanmengmeng9 小时前
分布式追踪与监控:Skywalking介绍(一)
分布式·skywalking
HanhahnaH9 小时前
Redis单线程和Tair多线程架构设计对比
分布式·缓存
rustfs9 小时前
MinIO 国产开源平替正式 GA
分布式·docker·云原生·rust
螺蛳粉 螺蛳粉12 小时前
MySQL 分布式集群系列 · 第五篇——全方位对比:NDB、MGR、主从复制、分库分表怎么选?
数据库·分布式·mysql
孙启超13 小时前
【AI开发之Rust】第 7 课:错误处理 —— panic、Result 与 `?`
人工智能·分布式·后端·爬虫·spring cloud·架构·rust
九皇叔叔16 小时前
Seata——把分布式事务理论落到 Java 微服务实践
分布式·分布式事务·cap·base·saga
程序员黎剑21 小时前
RabbitMQ-消息可靠性-publisher-confirm持久化与手动ack
分布式·rabbitmq·ruby
比奥利奥还傲.1 天前
哪吒监控面板实战:部署 Dashboard、接入 Agent、钉钉告警,再配置固定公网访问
网络·人工智能·分布式·1024程序员节
拼图2091 天前
Git常用语法
分布式·git·学习
盟道科技2 天前
小程序订阅消息大规模投递实践:频控令牌池、Redis限流与失败补偿设计
分布式·算法·小程序