Redisson延迟队列遇到的坑

一、问题描述

做个Redisson延迟任务踩了好多坑。

1、项目启动时报Unexpected exception while processing command

2、经常性Redis server response timeout (3000 ms)

3、项目启动那一刻消费任务队列中积压的任务,项目运行过程中不消费

4、使用rbucket做幂等,set延时导致旧值覆盖新值,幂等失败

二、解决方法(可能只适用我个人) 

1、项目启动时报Unexpected exception while processing command

(1)一开始是延迟任务不起效,按照网上的解决方案加了:

redissonClient.getDelayedQueue(blockingFairQueue)
public <T> void runByType(RedisDelayedQueueTaskListener taskEventListener, String queueName) {
        RBlockingQueue<T> blockingFairQueue = redissonClient.getBlockingQueue(queueName);
        //redissonClient.getDelayedQueue(blockingFairQueue);//项目启动时报错
        ((Runnable) () -> {
            while (true) {
                try {
                    log.error("我来了!");
                    T t = blockingFairQueue.take();//如果没有元素,则阻塞队列
                    if (t != null) {
                        log.error("我进来了!");
                        taskEventListener.invoke(t);
                    }
                    log.error("我还在!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).run();
    }

然而任务还是不起效。并且项目启动时报如标题的错。

根据源码,这段代码的在这里的作用是创建底层的时间轮定时任务:如果有旧的定时任务,那么使用旧的定时任务。duBug结果是每次都能拿到还在跑的旧定时任务。所以把这个语句去掉了。

(2)去掉上面这段代码后,Unexpected exception报错还在。

改为用Spring容器初始化队列后解决。

    /**
     * 添加机器人
     */
    @Bean(name = "delayedQueueRobotCreate")
    public RDelayedQueue<XXX> delayedQueueRobotCreate(@Qualifier("blockingQueueRobotCreate") RBlockingQueue blockingQueue) {
        RDelayedQueue<XXX> carIdRDelayedQueue = redissonClient.getDelayedQueue(blockingQueue);
        return carIdRDelayedQueue;
    }

    /**
     * 添加机器人
     */
    @Bean(name = "blockingQueueRobotCreate")
    public RBlockingQueue<XXX> blockingQueueRobotCreate() {
        RBlockingQueue<XXX> carIdRBlockingQueue = redissonClient.getBlockingQueue(TaskQueueType.ROBOT_CREATE.getName());
        return carIdRBlockingQueue;
    }

2、经常性Redis server response timeout (3000 ms)

(1)添加定时任务的时候需要用redisson做幂等,在set的时候三次有一次timeOut

使用下面的方法大致解决:

A.首先配置

/**resdisson配置心跳,设置空闲超时时间(原设为60,后发现单位为毫秒)*/
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson() throws IOException {
        Config config = new Config();
        config.setExecutor(Executors.cacheExecutor)
                .useSingleServer()
                .setAddress("redis://localhost:6379")
                .setPingConnectionInterval(1000)//1秒发一次心跳,默认是30秒
                .setConnectionPoolSize(8)
                .setConnectionMinimumIdleSize(8)
                .setIdleConnectionTimeout(60000)//60秒,默认是10秒
                .setClientName("xxxx")
                .setKeepAlive(true)
                .setTcpNoDelay(true);
        return Redisson.create(config);
    }

B.然后异步

CompletableFuture fs = CompletableFuture.runAsync(() -> {
            try {
                log.warn("用户[{}]XXXX[{}],触发“XXXX”定时任务", userId, XXXId);
                cacheUtils.setAsync(now, RedisCacheKey.FORMATION_SUCCESS, carId);//幂等处理:定时任务中跟XXXX.update_at比较
                redisDelayedQueueUtils.addQueueFormationSuccessionFuture(xxxx, TaskQueueType.FORMATION_SUCCESS.getDuration(), TaskQueueType.FORMATION_SUCCESS.getTimeUnit());//5分钟
            } catch (Exception e) {
                e.printStackTrace();
                log.error("用户[{}]XXXX[{}],触发“XXXX”定时任务,触发失败!ERR", userId, XXXId);
            }
        }, Executors.formationSucccessExecutor);

3、项目启动那一刻消费任务队列中积压的任务,项目运行过程中不消费

最后一个坑在队列的take()方法:如果没有元素,则阻塞队列直到队列中有任务后返回

经过各种调试,在项目刚启动时take会获取并消费任务,阻塞和返回过程也正常,但是消费几次就不消费了,我不理解。

当两个定时任务使用同一个线程池时则项目启动时也不消费,我不理解。

最后改为poll方法:如果没有元素,则阻塞一定时长后返回。

public void runRobotCreate(RedisDelayedQueueTaskListener taskEventListener) {
        ((Runnable) () -> {
            while (true) {
                try {
                    //10秒后返回
                    XXX xxx = blockingQueueRobotCreate.poll(10, TimeUnit.SECONDS);
                    if (xxx != null) {
                        taskEventListener.invoke(xxx);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    log.error("我要被中断了!RobotCreate");
                }
            }
        }).run();
    }

4、使用rbucket做幂等,set延时导致旧值覆盖新值,幂等失败

业务描述:用户点击某个功能开关,半小时后功能才开始起作用,并且每五分钟功能运行一次。

加个5分钟的定时任务,扫表找到打开了开关的用户,运行功能;

加个30分钟的延时队列,开关在半小时后才实际打开(写库),否则会被定时任务扫到;

开关可多次点击,会添加多个延迟任务到队列中,需要做好幂等,只有最后一个延迟任务要起效的,其他的废弃。

有两种方案:

(1)表里面加一个字段表示点击状态,相当于一个开关功能有两个字段,不是很友好;

(2)缓存中设置一个值(可以用时间戳),每次点击都更新这个值,并且这个值也设置进延时队列Data中,每次取出任务后比较;

使用了第二种方案,但是多次点击开关后,redisson.set存在延时,旧值覆盖新值,幂等失败。

解决方案:用zset。拿最大的那个值(时间戳)。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Redisson 是一个基于 Redis 的 Java 库,它提供了丰富的分布式数据结构和服务,其中包括延迟队列Redisson延迟队列基于 Redis 的有序集合(Sorted Set)实现,通过设置元素的 score 值来实现延迟。元素的 score 值表示元素应该在何时被消费,Redisson 会定期扫描有序集合,找到 score 值小于当前时间的元素进行消费。 下面是一个使用 Redisson 延迟队列的示例代码: ```java // 创建 Redisson 客户端 Config config = new Config(); config.useSingleServer().setAddress("redis://127.0.0.1:6379"); RedissonClient redisson = Redisson.create(config); // 获取延迟队列 RDelayedQueue<String> delayedQueue = redisson.getDelayedQueue(redisson.getQueue("myQueue")); // 添加元素到延迟队列 delayedQueue.offer("hello", 10, TimeUnit.SECONDS); // 10 秒后消费 // 创建消费者线程 new Thread(() -> { RBlockingQueue<String> blockingQueue = redisson.getBlockingQueue("myQueue"); while (!Thread.interrupted()) { try { String item = blockingQueue.take(); System.out.println("consume item: " + item); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }).start(); ``` 上面的示例代码中,首先创建了一个 Redisson 客户端。然后通过 `redisson.getDelayedQueue()` 方法获取了延迟队列对象 `delayedQueue`,并通过 `delayedQueue.offer()` 方法向队列中添加了一个元素,该元素将在 10 秒后被消费。 最后创建了一个消费者线程,通过 `redisson.getBlockingQueue()` 方法获取了阻塞队列对象 `blockingQueue`,并通过 `blockingQueue.take()` 方法从队列中取出元素进行消费。 需要注意的是,上面的示例代码中没有关闭 Redisson 客户端,实际使用中需要在程序退出时调用 `redisson.shutdown()` 方法关闭客户端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值