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);
    }
}
相关推荐
小邓吖2 小时前
自己做了一个工具网站
前端·分布式·后端·中间件·架构·golang
曹天骄6 小时前
基于 Cloudflare Worker 构建分布式测速调度系统:KV 与 D1 数据层设计实战教程
分布式·缓存
Prince-Peng8 小时前
技术架构系列 - 详解Redis
数据结构·数据库·redis·分布式·缓存·中间件·架构
曹天骄10 小时前
基于 Cloudflare Worker + KV 构建高性能分布式测速调度系统(工程实战)
分布式
奋进的芋圆11 小时前
Spring Boot 3 高并发事务与分布式事务企业级完整解决方案
spring boot·分布式
淡泊if11 小时前
Kafka部署模式详解:从单机到分布式集群的核心选择
分布式·kafka
鱼跃鹰飞11 小时前
面试题:什么是时钟回拨问题?怎么解决
分布式·系统架构
无心水11 小时前
分布式环境下定时任务与SELECT FOR UPDATE的陷阱与解决方案
分布式·后端·wpf·xxl-job·quartz·定时任务·selectforupdate
缘友一世12 小时前
大模型分布式推理:Ray 与 vLLM/Transformers 的协同架构深度解析
分布式·架构·transformer·ray·vllm
亚里随笔12 小时前
MegaFlow:面向Agent时代的大规模分布式编排系统
人工智能·分布式·llm·rl·agentic