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);
    }
}
相关推荐
m0_736034851 小时前
ceph分布式存储
分布式·ceph
冷色调的咖啡师2 小时前
1.大数据架构技术 上——搭建分布式Hadoop集群
大数据·linux·hadoop·分布式·hdfs·架构·yarn
坤昱18 小时前
cfs调度类深入解刨——最新内核细节分析5
linux·分布式·cfs调度·eevdf调度·linux调度·linux技术·kernel最新版本内容
AI人工智能+电脑小能手18 小时前
【大白话说Java面试题 第91题】【Mysql篇】第21题:分布式锁的使用场景和原理?
java·数据库·分布式·mysql·面试
JAVA社区18 小时前
Java高级全套教程(十三)—— 分布式锁超详细实战详解(原理+三种方案企业级落地)
java·开发语言·分布式·spring cloud·面试·java-zookeeper
Leo18719 小时前
分布式事务
java·分布式·分布式事务
潮起鲸落入海1 天前
ceph分布式存储认证和授权,块存储管理
分布式·ceph
ZPC82101 天前
前馈补偿原理 + 分类 + 公式 + 工程实现(配合 PID 使用,从根源减轻闭环收敛压力)
人工智能·分布式·机器人
闪电悠米1 天前
黑马点评-分布式锁-02_simple_redis_lock_setnx
java·数据库·spring boot·redis·分布式·缓存·wpf
大迪deblog1 天前
从分布式到中央计算:深度拆解下一代 Zonal 车载 EEA 架构变革
分布式·架构