延迟任务概述

什么是延迟任务

定时任务:有固定周期的,有明确的触发时间

延迟任务:没有固定的开始时间,它常常是由一个事件触发的,而在这个事件触发之后的一段时间内触发另一个事件,任务可以立即执行,也可以延迟

DelayQueue实现延迟任务

JDK自带DelayQueue 是一个支持延时获取元素的阻塞队列, 内部采用优先队列 PriorityQueue 存储元素,同时元素必须实现 Delayed 接口;在创建元素时可以指定多久才可以从队列中获取当前元素,只有在延迟期满时才能从队列中提取元素

缺点:使用DelayQueue作为延迟任务,如果程序挂掉之后,任务都是放在内存,消息会丢失,如何保证数据不丢失

RabbitMQ实现延迟任务

TTL:Time To Live (消息存活时间) 死信队列:Dead Letter Exchange(死信交换机),当消息成为Dead message后,可以重新发送另一个交换机(死信交换机)

redis实现

zset数据类型的去重有序(分数排序)特点进行延迟。例如:时间戳(毫秒值)作为score进行排序

例如: 生产者添加到4个任务到延迟队列中,时间毫秒值分别为97、98、99、100。当前时间的毫秒值为90 消费者端进行监听,如果当前时间的毫秒值匹配到了延迟队列中的毫秒值就立即消费

redis实现延迟任务

redis定时任务使用到的两者数据类型:list和zset,立即执行的任务用list,未来执行的任务用zest

list的特点:在redis中是双线链表,可以很方便的进行添加和查找,并且性能很高

zset的特点:可以按照分值(这里的分值指的是定时任务的时间戳)进行排序,存储未来要执行的任务,如果当前时间的毫秒值匹配到了延迟队列的毫秒值就会立即消费

list通过左push将消息添加到list集合,然后通过右pop将数据取出让消费者进行消费

数据库中的任务进行定时同步,超过五分钟的定时任务暂存到DB中,小于五分钟的定时任务存入到redis中的zset中,原因是防止redis中数据量过大,导致zset产生阻塞。

存储到redis中zset的数据每分钟把到期的任务刷新到list中进行消费

redis的数据结构

问题一:为什么任务需要存储在数据库中?

延迟任务是一个通用的服务,任何有延迟需求的任务都可以调用该服务,内存数据库的存储是有限的,并且为了数据安全考虑,防止程序挂掉后,消息丢失的问题,需要考虑数据持久化的问题,存储数据库中是一种数据安全的考虑。

问题二:为什么使用redis中的两种数据类型,list和zset?

原因一:list存储立即执行的任务,zset存储未来的数据

原因二:任务量过大以后,zset的性能会下降

时间复杂度:执行时间(次数)随着数据规模增长的变化趋势

用redis实现延迟任务

1.准备微服务

heima-leadnews-schedule是一个通用的服务,单独创建模块来管理任何类型的延迟任务

2.数据库准备

数据库准备-数据库自身解决并发两种策略:悲观锁和乐观锁
一、悲观锁(Pessimistic Lock) 每次去拿数据的时候都认为别人会修改,所以每次在拿数据的时候都会上锁。

二、乐观锁(Optimistic Lock) 每次去拿数据的时候都认为别人不会修改,所以不会上锁,但是在更新的时候会判断一下在此期间别人有没有去更新这个数据,可以使用版本号等机制

 

(MySQL中,BLOB是一个二进制大型对象,是一个可以存储大量数据的容器;LongBlob 最大存储 4G)

通过version来进行判断,如果要进行更新时,先记一下版本号,然后修改完成回来判断一下版本号是不是原来的,如果不是原来的说明里面的数据以及被操作过了,此时就不能提交事务了

    3.数据库准备-mybatis-plus集成乐观锁的使用

    ①:在实体类中使用@Version标明是一个版本的字段

    ②:mybatis-plus对乐观锁的支持,在启动类中向容器中放入乐观锁的拦截器

    /**
         * mybatis-plus乐观锁支持
         * @return
         */
    @Bean
    public MybatisPlusInterceptor optimisticLockerInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }

    4.安装redis

    5.项目集成redis

    ①  在项目导入redis相关依赖,已经完成

      <!--spring data redis & cache-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
            <!-- redis依赖commons-pool 这个依赖一定要添加 -->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
            </dependency>

    ②  在heima-leadnews-schedule中集成redis,添加以下nacos配置,链接上redis

    spring:
      redis:
        host: 192.168.200.130
        password: leadnews
        port: 6379

    ③  拷贝资料文件夹下的类:CacheService到heima-leadnews-common模块下,并添加自动配置

    package com.heima.schedule.config;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.dao.DataAccessException;
    import org.springframework.data.redis.connection.DataType;
    import org.springframework.data.redis.connection.RedisConnection;
    import org.springframework.data.redis.connection.StringRedisConnection;
    import org.springframework.data.redis.core.Cursor;
    import org.springframework.data.redis.core.RedisCallback;
    import org.springframework.data.redis.core.ScanOptions;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
    import org.springframework.lang.Nullable;
    import org.springframework.stereotype.Component;
    
    import java.io.IOException;
    import java.util.*;
    import java.util.concurrent.TimeUnit;
    
    @Component
    public class CacheService extends CachingConfigurerSupport {
        @Autowired
        private StringRedisTemplate stringRedisTemplate;
    
        public StringRedisTemplate getstringRedisTemplate() {
            return this.stringRedisTemplate;
        }
    
        /** -------------------key相关操作--------------------- */
    
        /**
         * 删除key
         *
         * @param key
         */
        public void delete(String key) {
            stringRedisTemplate.delete(key);
        }
    
        /**
         * 批量删除key
         *
         * @param keys
         */
        public void delete(Collection<String> keys) {
            stringRedisTemplate.delete(keys);
        }
    
        /**
         * 序列化key
         *
         * @param key
         * @return
         */
        public byte[] dump(String key) {
            return stringRedisTemplate.dump(key);
        }
    
        /**
         * 是否存在key
         *
         * @param key
         * @return
         */
        public Boolean exists(String key) {
            return stringRedisTemplate.hasKey(key);
        }
    
        /**
         * 设置过期时间
         *
         * @param key
         * @param timeout
         * @param unit
         * @return
         */
        public Boolean expire(String key, long timeout, TimeUnit unit) {
            return stringRedisTemplate.expire(key, timeout, unit);
        }
    
        /**
         * 设置过期时间
         *
         * @param key
         * @param date
         * @return
         */
        public Boolean expireAt(String key, Date date) {
            return stringRedisTemplate.expireAt(key, date);
        }
    
        /**
         * 查找匹配的key
         *
         * @param pattern
         * @return
         */
        public Set<String> keys(String pattern) {
            return stringRedisTemplate.keys(pattern);
        }
    
        /**
         * 将当前数据库的 key 移动到给定的数据库 db 当中
         *
         * @param key
         * @param dbIndex
         * @return
         */
        public Boolean move(String key, int dbIndex) {
            return stringRedisTemplate.move(key, dbIndex);
        }
    
        /**
         * 移除 key 的过期时间,key 将持久保持
         *
         * @param key
         * @return
         */
        public Boolean persist(String key) {
            return stringRedisTemplate.persist(key);
        }
    
        /**
         * 返回 key 的剩余的过期时间
         *
         * @param key
         * @param unit
         * @return
         */
        public Long getExpire(String key, TimeUnit unit) {
            return stringRedisTemplate.getExpire(key, unit);
        }
    
        /**
         * 返回 key 的剩余的过期时间
         *
         * @param key
         * @return
         */
        public Long getExpire(String key) {
            return stringRedisTemplate.getExpire(key);
        }
    
        /**
         * 从当前数据库中随机返回一个 key
         *
         * @return
         */
        public String randomKey() {
            return stringRedisTemplate.randomKey();
        }
    
        /**
         * 修改 key 的名称
         *
         * @param oldKey
         * @param newKey
         */
        public void rename(String oldKey, String newKey) {
            stringRedisTemplate.rename(oldKey, newKey);
        }
    
        /**
         * 仅当 newkey 不存在时,将 oldKey 改名为 newkey
         *
         * @param oldKey
         * @param newKey
         * @return
         */
        public Boolean renameIfAbsent(String oldKey, String newKey) {
            return stringRedisTemplate.renameIfAbsent(oldKey, newKey);
        }
    
        /**
         * 返回 key 所储存的值的类型
         *
         * @param key
         * @return
         */
        public DataType type(String key) {
            return stringRedisTemplate.type(key);
        }
    
        /** -------------------string相关操作--------------------- */
    
        /**
         * 设置指定 key 的值
         * @param key
         * @param value
         */
        public void set(String key, String value) {
            stringRedisTemplate.opsForValue().set(key, value);
        }
    
        /**
         * 获取指定 key 的值
         * @param key
         * @return
         */
        public String get(String key) {
            return stringRedisTemplate.opsForValue().get(key);
        }
    
        /**
         * 返回 key 中字符串值的子字符
         * @param key
         * @param start
         * @param end
         * @return
         */
        public String getRange(String key, long start, long end) {
            return stringRedisTemplate.opsForValue().get(key, start, end);
        }
    
        /**
         * 将给定 key 的值设为 value ,并返回 key 的旧值(old value)
         *
         * @param key
         * @param value
         * @return
         */
        public String getAndSet(String key, String value) {
            return stringRedisTemplate.opsForValue().getAndSet(key, value);
        }
    
        /**
         * 对 key 所储存的字符串值,获取指定偏移量上的位(bit)
         *
         * @param key
         * @param offset
         * @return
         */
        public Boolean getBit(String key, long offset) {
            return stringRedisTemplate.opsForValue().getBit(key, offset);
        }
    
        /**
         * 批量获取
         *
         * @param keys
         * @return
         */
        public List<String> multiGet(Collection<String> keys) {
            return stringRedisTemplate.opsForValue().multiGet(keys);
        }
    
        /**
         * 设置ASCII码, 字符串'a'的ASCII码是97, 转为二进制是'01100001', 此方法是将二进制第offset位值变为value
         *
         * @param key
         * @param
         * @param value
         *            值,true为1, false为0
         * @return
         */
        public boolean setBit(String key, long offset, boolean value) {
            return stringRedisTemplate.opsForValue().setBit(key, offset, value);
        }
    
        /**
         * 将值 value 关联到 key ,并将 key 的过期时间设为 timeout
         *
         * @param key
         * @param value
         * @param timeout
         *            过期时间
         * @param unit
         *            时间单位, 天:TimeUnit.DAYS 小时:TimeUnit.HOURS 分钟:TimeUnit.MINUTES
         *            秒:TimeUnit.SECONDS 毫秒:TimeUnit.MILLISECONDS
         */
        public void setEx(String key, String value, long timeout, TimeUnit unit) {
            stringRedisTemplate.opsForValue().set(key, value, timeout, unit);
        }
    
        /**
         * 只有在 key 不存在时设置 key 的值
         *
         * @param key
         * @param value
         * @return 之前已经存在返回false,不存在返回true
         */
        public boolean setIfAbsent(String key, String value) {
            return stringRedisTemplate.opsForValue().setIfAbsent(key, value);
        }
    
        /**
         * 用 value 参数覆写给定 key 所储存的字符串值,从偏移量 offset 开始
         *
         * @param key
         * @param value
         * @param offset
         *            从指定位置开始覆写
         */
        public void setRange(String key, String value, long offset) {
            stringRedisTemplate.opsForValue().set(key, value, offset);
        }
    
        /**
         * 获取字符串的长度
         *
         * @param key
         * @return
         */
        public Long size(String key) {
            return stringRedisTemplate.opsForValue().size(key);
        }
    
        /**
         * 批量添加
         *
         * @param maps
         */
        public void multiSet(Map<String, String> maps) {
            stringRedisTemplate.opsForValue().multiSet(maps);
        }
    
        /**
         * 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在
         *
         * @param maps
         * @return 之前已经存在返回false,不存在返回true
         */
        public boolean multiSetIfAbsent(Map<String, String> maps) {
            return stringRedisTemplate.opsForValue().multiSetIfAbsent(maps);
        }
    
        /**
         * 增加(自增长), 负数则为自减
         *
         * @param key
         * @param
         * @return
         */
        public Long incrBy(String key, long increment) {
            return stringRedisTemplate.opsForValue().increment(key, increment);
        }
    
        /**
         *
         * @param key
         * @param
         * @return
         */
        public Double incrByFloat(String key, double increment) {
            return stringRedisTemplate.opsForValue().increment(key, increment);
        }
    
        /**
         * 追加到末尾
         *
         * @param key
         * @param value
         * @return
         */
        public Integer append(String key, String value) {
            return stringRedisTemplate.opsForValue().append(key, value);
        }
    
        /** -------------------hash相关操作------------------------- */
    
        /**
         * 获取存储在哈希表中指定字段的值
         *
         * @param key
         * @param field
         * @return
         */
        public Object hGet(String key, String field) {
            return stringRedisTemplate.opsForHash().get(key, field);
        }
    
        /**
         * 获取所有给定字段的值
         *
         * @param key
         * @return
         */
        public Map<Object, Object> hGetAll(String key) {
            return stringRedisTemplate.opsForHash().entries(key);
        }
    
        /**
         * 获取所有给定字段的值
         *
         * @param key
         * @param fields
         * @return
         */
        public List<Object> hMultiGet(String key, Collection<Object> fields) {
            return stringRedisTemplate.opsForHash().multiGet(key, fields);
        }
    
        public void hPut(String key, String hashKey, String value) {
            stringRedisTemplate.opsForHash().put(key, hashKey, value);
        }
    
        public void hPutAll(String key, Map<String, String> maps) {
            stringRedisTemplate.opsForHash().putAll(key, maps);
        }
    
        /**
         * 仅当hashKey不存在时才设置
         *
         * @param key
         * @param hashKey
         * @param value
         * @return
         */
        public Boolean hPutIfAbsent(String key, String hashKey, String value) {
            return stringRedisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
        }
    
        /**
         * 删除一个或多个哈希表字段
         *
         * @param key
         * @param fields
         * @return
         */
        public Long hDelete(String key, Object... fields) {
            return stringRedisTemplate.opsForHash().delete(key, fields);
        }
    
        /**
         * 查看哈希表 key 中,指定的字段是否存在
         *
         * @param key
         * @param field
         * @return
         */
        public boolean hExists(String key, String field) {
            return stringRedisTemplate.opsForHash().hasKey(key, field);
        }
    
        /**
         * 为哈希表 key 中的指定字段的整数值加上增量 increment
         *
         * @param key
         * @param field
         * @param increment
         * @return
         */
        public Long hIncrBy(String key, Object field, long increment) {
            return stringRedisTemplate.opsForHash().increment(key, field, increment);
        }
    
        /**
         * 为哈希表 key 中的指定字段的整数值加上增量 increment
         *
         * @param key
         * @param field
         * @param delta
         * @return
         */
        public Double hIncrByFloat(String key, Object field, double delta) {
            return stringRedisTemplate.opsForHash().increment(key, field, delta);
        }
    
        /**
         * 获取所有哈希表中的字段
         *
         * @param key
         * @return
         */
        public Set<Object> hKeys(String key) {
            return stringRedisTemplate.opsForHash().keys(key);
        }
    
        /**
         * 获取哈希表中字段的数量
         *
         * @param key
         * @return
         */
        public Long hSize(String key) {
            return stringRedisTemplate.opsForHash().size(key);
        }
    
        /**
         * 获取哈希表中所有值
         *
         * @param key
         * @return
         */
        public List<Object> hValues(String key) {
            return stringRedisTemplate.opsForHash().values(key);
        }
    
        /**
         * 迭代哈希表中的键值对
         *
         * @param key
         * @param options
         * @return
         */
        public Cursor<Map.Entry<Object, Object>> hScan(String key, ScanOptions options) {
            return stringRedisTemplate.opsForHash().scan(key, options);
        }
    
        /** ------------------------list相关操作---------------------------- */
    
        /**
         * 通过索引获取列表中的元素
         *
         * @param key
         * @param index
         * @return
         */
        public String lIndex(String key, long index) {
            return stringRedisTemplate.opsForList().index(key, index);
        }
    
        /**
         * 获取列表指定范围内的元素
         *
         * @param key
         * @param start
         *            开始位置, 0是开始位置
         * @param end
         *            结束位置, -1返回所有
         * @return
         */
        public List<String> lRange(String key, long start, long end) {
            return stringRedisTemplate.opsForList().range(key, start, end);
        }
    
        /**
         * 存储在list头部
         *
         * @param key
         * @param value
         * @return
         */
        public Long lLeftPush(String key, String value) {
            return stringRedisTemplate.opsForList().leftPush(key, value);
        }
    
        /**
         *
         * @param key
         * @param value
         * @return
         */
        public Long lLeftPushAll(String key, String... value) {
            return stringRedisTemplate.opsForList().leftPushAll(key, value);
        }
    
        /**
         *
         * @param key
         * @param value
         * @return
         */
        public Long lLeftPushAll(String key, Collection<String> value) {
            return stringRedisTemplate.opsForList().leftPushAll(key, value);
        }
    
        /**
         * 当list存在的时候才加入
         *
         * @param key
         * @param value
         * @return
         */
        public Long lLeftPushIfPresent(String key, String value) {
            return stringRedisTemplate.opsForList().leftPushIfPresent(key, value);
        }
    
        /**
         * 如果pivot存在,再pivot前面添加
         *
         * @param key
         * @param pivot
         * @param value
         * @return
         */
        public Long lLeftPush(String key, String pivot, String value) {
            return stringRedisTemplate.opsForList().leftPush(key, pivot, value);
        }
    
        /**
         *
         * @param key
         * @param value
         * @return
         */
        public Long lRightPush(String key, String value) {
            return stringRedisTemplate.opsForList().rightPush(key, value);
        }
    
        /**
         *
         * @param key
         * @param value
         * @return
         */
        public Long lRightPushAll(String key, String... value) {
            return stringRedisTemplate.opsForList().rightPushAll(key, value);
        }
    
        /**
         *
         * @param key
         * @param value
         * @return
         */
        public Long lRightPushAll(String key, Collection<String> value) {
            return stringRedisTemplate.opsForList().rightPushAll(key, value);
        }
    
        /**
         * 为已存在的列表添加值
         *
         * @param key
         * @param value
         * @return
         */
        public Long lRightPushIfPresent(String key, String value) {
            return stringRedisTemplate.opsForList().rightPushIfPresent(key, value);
        }
    
        /**
         * 在pivot元素的右边添加值
         *
         * @param key
         * @param pivot
         * @param value
         * @return
         */
        public Long lRightPush(String key, String pivot, String value) {
            return stringRedisTemplate.opsForList().rightPush(key, pivot, value);
        }
    
        /**
         * 通过索引设置列表元素的值
         *
         * @param key
         * @param index
         *            位置
         * @param value
         */
        public void lSet(String key, long index, String value) {
            stringRedisTemplate.opsForList().set(key, index, value);
        }
    
        /**
         * 移出并获取列表的第一个元素
         *
         * @param key
         * @return 删除的元素
         */
        public String lLeftPop(String key) {
            return stringRedisTemplate.opsForList().leftPop(key);
        }
    
        /**
         * 移出并获取列表的第一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
         *
         * @param key
         * @param timeout
         *            等待时间
         * @param unit
         *            时间单位
         * @return
         */
        public String lBLeftPop(String key, long timeout, TimeUnit unit) {
            return stringRedisTemplate.opsForList().leftPop(key, timeout, unit);
        }
    
        /**
         * 移除并获取列表最后一个元素
         *
         * @param key
         * @return 删除的元素
         */
        public String lRightPop(String key) {
            return stringRedisTemplate.opsForList().rightPop(key);
        }
    
        /**
         * 移出并获取列表的最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
         *
         * @param key
         * @param timeout
         *            等待时间
         * @param unit
         *            时间单位
         * @return
         */
        public String lBRightPop(String key, long timeout, TimeUnit unit) {
            return stringRedisTemplate.opsForList().rightPop(key, timeout, unit);
        }
    
        /**
         * 移除列表的最后一个元素,并将该元素添加到另一个列表并返回
         *
         * @param sourceKey
         * @param destinationKey
         * @return
         */
        public String lRightPopAndLeftPush(String sourceKey, String destinationKey) {
            return stringRedisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
                    destinationKey);
        }
    
        /**
         * 从列表中弹出一个值,将弹出的元素插入到另外一个列表中并返回它; 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
         *
         * @param sourceKey
         * @param destinationKey
         * @param timeout
         * @param unit
         * @return
         */
        public String lBRightPopAndLeftPush(String sourceKey, String destinationKey,
                                            long timeout, TimeUnit unit) {
            return stringRedisTemplate.opsForList().rightPopAndLeftPush(sourceKey,
                    destinationKey, timeout, unit);
        }
        
        /**
         * 删除集合中值等于value得元素
         *
         * @param key
         * @param index
         *            index=0, 删除所有值等于value的元素; index>0, 从头部开始删除第一个值等于value的元素;
         *            index<0, 从尾部开始删除第一个值等于value的元素;
         * @param value
         * @return
         */
        public Long lRemove(String key, long index, String value) {
            return stringRedisTemplate.opsForList().remove(key, index, value);
        }
    
        /**
         * 裁剪list
         *
         * @param key
         * @param start
         * @param end
         */
        public void lTrim(String key, long start, long end) {
            stringRedisTemplate.opsForList().trim(key, start, end);
        }
    
        /**
         * 获取列表长度
         *
         * @param key
         * @return
         */
        public Long lLen(String key) {
            return stringRedisTemplate.opsForList().size(key);
        }
    
    
        /** --------------------set相关操作-------------------------- */
    
        /**
         * set添加元素
         *
         * @param key
         * @param values
         * @return
         */
        public Long sAdd(String key, String... values) {
            return stringRedisTemplate.opsForSet().add(key, values);
        }
    
        /**
         * set移除元素
         *
         * @param key
         * @param values
         * @return
         */
        public Long sRemove(String key, Object... values) {
            return stringRedisTemplate.opsForSet().remove(key, values);
        }
    
        /**
         * 移除并返回集合的一个随机元素
         *
         * @param key
         * @return
         */
        public String sPop(String key) {
            return stringRedisTemplate.opsForSet().pop(key);
        }
    
        /**
         * 将元素value从一个集合移到另一个集合
         *
         * @param key
         * @param value
         * @param destKey
         * @return
         */
        public Boolean sMove(String key, String value, String destKey) {
            return stringRedisTemplate.opsForSet().move(key, value, destKey);
        }
    
        /**
         * 获取集合的大小
         *
         * @param key
         * @return
         */
        public Long sSize(String key) {
            return stringRedisTemplate.opsForSet().size(key);
        }
    
        /**
         * 判断集合是否包含value
         *
         * @param key
         * @param value
         * @return
         */
        public Boolean sIsMember(String key, Object value) {
            return stringRedisTemplate.opsForSet().isMember(key, value);
        }
    
        /**
         * 获取两个集合的交集
         *
         * @param key
         * @param otherKey
         * @return
         */
        public Set<String> sIntersect(String key, String otherKey) {
            return stringRedisTemplate.opsForSet().intersect(key, otherKey);
        }
    
        /**
         * 获取key集合与多个集合的交集
         *
         * @param key
         * @param otherKeys
         * @return
         */
        public Set<String> sIntersect(String key, Collection<String> otherKeys) {
            return stringRedisTemplate.opsForSet().intersect(key, otherKeys);
        }
    
        /**
         * key集合与otherKey集合的交集存储到destKey集合中
         *
         * @param key
         * @param otherKey
         * @param destKey
         * @return
         */
        public Long sIntersectAndStore(String key, String otherKey, String destKey) {
            return stringRedisTemplate.opsForSet().intersectAndStore(key, otherKey,
                    destKey);
        }
    
        /**
         * key集合与多个集合的交集存储到destKey集合中
         *
         * @param key
         * @param otherKeys
         * @param destKey
         * @return
         */
        public Long sIntersectAndStore(String key, Collection<String> otherKeys,
                                       String destKey) {
            return stringRedisTemplate.opsForSet().intersectAndStore(key, otherKeys,
                    destKey);
        }
    
        /**
         * 获取两个集合的并集
         *
         * @param key
         * @param otherKeys
         * @return
         */
        public Set<String> sUnion(String key, String otherKeys) {
            return stringRedisTemplate.opsForSet().union(key, otherKeys);
        }
    
        /**
         * 获取key集合与多个集合的并集
         *
         * @param key
         * @param otherKeys
         * @return
         */
        public Set<String> sUnion(String key, Collection<String> otherKeys) {
            return stringRedisTemplate.opsForSet().union(key, otherKeys);
        }
    
        /**
         * key集合与otherKey集合的并集存储到destKey中
         *
         * @param key
         * @param otherKey
         * @param destKey
         * @return
         */
        public Long sUnionAndStore(String key, String otherKey, String destKey) {
            return stringRedisTemplate.opsForSet().unionAndStore(key, otherKey, destKey);
        }
    
        /**
         * key集合与多个集合的并集存储到destKey中
         *
         * @param key
         * @param otherKeys
         * @param destKey
         * @return
         */
        public Long sUnionAndStore(String key, Collection<String> otherKeys,
                                   String destKey) {
            return stringRedisTemplate.opsForSet().unionAndStore(key, otherKeys, destKey);
        }
    
        /**
         * 获取两个集合的差集
         *
         * @param key
         * @param otherKey
         * @return
         */
        public Set<String> sDifference(String key, String otherKey) {
            return stringRedisTemplate.opsForSet().difference(key, otherKey);
        }
    
        /**
         * 获取key集合与多个集合的差集
         *
         * @param key
         * @param otherKeys
         * @return
         */
        public Set<String> sDifference(String key, Collection<String> otherKeys) {
            return stringRedisTemplate.opsForSet().difference(key, otherKeys);
        }
    
        /**
         * key集合与otherKey集合的差集存储到destKey中
         *
         * @param key
         * @param otherKey
         * @param destKey
         * @return
         */
        public Long sDifference(String key, String otherKey, String destKey) {
            return stringRedisTemplate.opsForSet().differenceAndStore(key, otherKey,
                    destKey);
        }
    
        /**
         * key集合与多个集合的差集存储到destKey中
         *
         * @param key
         * @param otherKeys
         * @param destKey
         * @return
         */
        public Long sDifference(String key, Collection<String> otherKeys,
                                String destKey) {
            return stringRedisTemplate.opsForSet().differenceAndStore(key, otherKeys,
                    destKey);
        }
    
        /**
         * 获取集合所有元素
         *
         * @param key
         * @param
         * @param
         * @return
         */
        public Set<String> setMembers(String key) {
            return stringRedisTemplate.opsForSet().members(key);
        }
    
        /**
         * 随机获取集合中的一个元素
         *
         * @param key
         * @return
         */
        public String sRandomMember(String key) {
            return stringRedisTemplate.opsForSet().randomMember(key);
        }
    
        /**
         * 随机获取集合中count个元素
         *
         * @param key
         * @param count
         * @return
         */
        public List<String> sRandomMembers(String key, long count) {
            return stringRedisTemplate.opsForSet().randomMembers(key, count);
        }
    
        /**
         * 随机获取集合中count个元素并且去除重复的
         *
         * @param key
         * @param count
         * @return
         */
        public Set<String> sDistinctRandomMembers(String key, long count) {
            return stringRedisTemplate.opsForSet().distinctRandomMembers(key, count);
        }
    
        /**
         *
         * @param key
         * @param options
         * @return
         */
        public Cursor<String> sScan(String key, ScanOptions options) {
            return stringRedisTemplate.opsForSet().scan(key, options);
        }
    
        /**------------------zSet相关操作--------------------------------*/
    
        /**
         * 添加元素,有序集合是按照元素的score值由小到大排列
         *
         * @param key
         * @param value
         * @param score
         * @return
         */
        public Boolean zAdd(String key, String value, double score) {
            return stringRedisTemplate.opsForZSet().add(key, value, score);
        }
    
        /**
         *
         * @param key
         * @param values
         * @return
         */
        public Long zAdd(String key, Set<TypedTuple<String>> values) {
            return stringRedisTemplate.opsForZSet().add(key, values);
        }
    
        /**
         *
         * @param key
         * @param values
         * @return
         */
        public Long zRemove(String key, Object... values) {
            return stringRedisTemplate.opsForZSet().remove(key, values);
        }
    
        public Long zRemove(String key, Collection<String> values) {
            if(values!=null&&!values.isEmpty()){
                Object[] objs = values.toArray(new Object[values.size()]);
                return stringRedisTemplate.opsForZSet().remove(key, objs);
            }
           return 0L;
        }
    
        /**
         * 增加元素的score值,并返回增加后的值
         *
         * @param key
         * @param value
         * @param delta
         * @return
         */
        public Double zIncrementScore(String key, String value, double delta) {
            return stringRedisTemplate.opsForZSet().incrementScore(key, value, delta);
        }
    
        /**
         * 返回元素在集合的排名,有序集合是按照元素的score值由小到大排列
         *
         * @param key
         * @param value
         * @return 0表示第一位
         */
        public Long zRank(String key, Object value) {
            return stringRedisTemplate.opsForZSet().rank(key, value);
        }
    
        /**
         * 返回元素在集合的排名,按元素的score值由大到小排列
         *
         * @param key
         * @param value
         * @return
         */
        public Long zReverseRank(String key, Object value) {
            return stringRedisTemplate.opsForZSet().reverseRank(key, value);
        }
    
        /**
         * 获取集合的元素, 从小到大排序
         *
         * @param key
         * @param start
         *            开始位置
         * @param end
         *            结束位置, -1查询所有
         * @return
         */
        public Set<String> zRange(String key, long start, long end) {
            return stringRedisTemplate.opsForZSet().range(key, start, end);
        }
        
        /**
         * 获取zset集合的所有元素, 从小到大排序
         *
         */
        public Set<String> zRangeAll(String key) {
            return zRange(key,0,-1);
        }
    
        /**
         * 获取集合元素, 并且把score值也获取
         *
         * @param key
         * @param start
         * @param end
         * @return
         */
        public Set<TypedTuple<String>> zRangeWithScores(String key, long start,
                                                        long end) {
            return stringRedisTemplate.opsForZSet().rangeWithScores(key, start, end);
        }
    
        /**
         * 根据Score值查询集合元素
         *
         * @param key
         * @param min
         *            最小值
         * @param max
         *            最大值
         * @return
         */
        public Set<String> zRangeByScore(String key, double min, double max) {
            return stringRedisTemplate.opsForZSet().rangeByScore(key, min, max);
        }
    
    
        /**
         * 根据Score值查询集合元素, 从小到大排序
         *
         * @param key
         * @param min
         *            最小值
         * @param max
         *            最大值
         * @return
         */
        public Set<TypedTuple<String>> zRangeByScoreWithScores(String key,
                                                               double min, double max) {
            return stringRedisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
        }
    
        /**
         *
         * @param key
         * @param min
         * @param max
         * @param start
         * @param end
         * @return
         */
        public Set<TypedTuple<String>> zRangeByScoreWithScores(String key,
                                                               double min, double max, long start, long end) {
            return stringRedisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max,
                    start, end);
        }
    
        /**
         * 获取集合的元素, 从大到小排序
         *
         * @param key
         * @param start
         * @param end
         * @return
         */
        public Set<String> zReverseRange(String key, long start, long end) {
            return stringRedisTemplate.opsForZSet().reverseRange(key, start, end);
    
        }
    
        public Set<String> zReverseRangeByScore(String key, long min, long max) {
            return stringRedisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
    
        }
    
        /**
         * 获取集合的元素, 从大到小排序, 并返回score值
         *
         * @param key
         * @param start
         * @param end
         * @return
         */
        public Set<TypedTuple<String>> zReverseRangeWithScores(String key,
                                                               long start, long end) {
            return stringRedisTemplate.opsForZSet().reverseRangeWithScores(key, start,
                    end);
        }
    
        /**
         * 根据Score值查询集合元素, 从大到小排序
         *
         * @param key
         * @param min
         * @param max
         * @return
         */
        public Set<String> zReverseRangeByScore(String key, double min,
                                                double max) {
            return stringRedisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
        }
    
        /**
         * 根据Score值查询集合元素, 从大到小排序
         *
         * @param key
         * @param min
         * @param max
         * @return
         */
        public Set<TypedTuple<String>> zReverseRangeByScoreWithScores(
                String key, double min, double max) {
            return stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key,
                    min, max);
        }
    
        /**
         *
         * @param key
         * @param min
         * @param max
         * @param start
         * @param end
         * @return
         */
        public Set<String> zReverseRangeByScore(String key, double min,
                                                double max, long start, long end) {
            return stringRedisTemplate.opsForZSet().reverseRangeByScore(key, min, max,
                    start, end);
        }
    
        /**
         * 根据score值获取集合元素数量
         *
         * @param key
         * @param min
         * @param max
         * @return
         */
        public Long zCount(String key, double min, double max) {
            return stringRedisTemplate.opsForZSet().count(key, min, max);
        }
    
        /**
         * 获取集合大小
         *
         * @param key
         * @return
         */
        public Long zSize(String key) {
            return stringRedisTemplate.opsForZSet().size(key);
        }
    
        /**
         * 获取集合大小
         *
         * @param key
         * @return
         */
        public Long zZCard(String key) {
            return stringRedisTemplate.opsForZSet().zCard(key);
        }
    
        /**
         * 获取集合中value元素的score值
         *
         * @param key
         * @param value
         * @return
         */
        public Double zScore(String key, Object value) {
            return stringRedisTemplate.opsForZSet().score(key, value);
        }
    
        /**
         * 移除指定索引位置的成员
         *
         * @param key
         * @param start
         * @param end
         * @return
         */
        public Long zRemoveRange(String key, long start, long end) {
            return stringRedisTemplate.opsForZSet().removeRange(key, start, end);
        }
    
        /**
         * 根据指定的score值的范围来移除成员
         *
         * @param key
         * @param min
         * @param max
         * @return
         */
        public Long zRemoveRangeByScore(String key, double min, double max) {
            return stringRedisTemplate.opsForZSet().removeRangeByScore(key, min, max);
        }
    
        /**
         * 获取key和otherKey的并集并存储在destKey中
         *
         * @param key
         * @param otherKey
         * @param destKey
         * @return
         */
        public Long zUnionAndStore(String key, String otherKey, String destKey) {
            return stringRedisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
        }
    
        /**
         *
         * @param key
         * @param otherKeys
         * @param destKey
         * @return
         */
        public Long zUnionAndStore(String key, Collection<String> otherKeys,
                                   String destKey) {
            return stringRedisTemplate.opsForZSet()
                    .unionAndStore(key, otherKeys, destKey);
        }
    
        /**
         * 交集
         *
         * @param key
         * @param otherKey
         * @param destKey
         * @return
         */
        public Long zIntersectAndStore(String key, String otherKey,
                                       String destKey) {
            return stringRedisTemplate.opsForZSet().intersectAndStore(key, otherKey,
                    destKey);
        }
    
        /**
         * 交集
         *
         * @param key
         * @param otherKeys
         * @param destKey
         * @return
         */
        public Long zIntersectAndStore(String key, Collection<String> otherKeys,
                                       String destKey) {
            return stringRedisTemplate.opsForZSet().intersectAndStore(key, otherKeys,
                    destKey);
        }
    
        /**
         *
         * @param key
         * @param options
         * @return
         */
        public Cursor<TypedTuple<String>> zScan(String key, ScanOptions options) {
            return stringRedisTemplate.opsForZSet().scan(key, options);
        }
    
        /**
         * 扫描主键,建议使用
         * @param patten
         * @return
         */
        public Set<String> scan(String patten){
            Set<String> keys = stringRedisTemplate.execute((RedisCallback<Set<String>>) connection -> {
                Set<String> result = new HashSet<>();
                try (Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder()
                        .match(patten).count(10000).build())) {
                    while (cursor.hasNext()) {
                        result.add(new String(cursor.next()));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return result;
            });
            return  keys;
        }
        
        /**
         * 管道技术,提高性能
         * @param type
         * @param values
         * @return
         */
        public List<Object> lRightPushPipeline(String type,Collection<String> values){
            List<Object> results = stringRedisTemplate.executePipelined(new RedisCallback<Object>() {
                        public Object doInRedis(RedisConnection connection) throws DataAccessException {
                            StringRedisConnection stringRedisConn = (StringRedisConnection)connection;
                            //集合转换数组
                            String[] strings = values.toArray(new String[values.size()]);
                            //直接批量发送
                            stringRedisConn.rPush(type, strings);
                            return null;
                        }
                    });
            return results;
        }
    
        public List<Object> refreshWithPipeline(String future_key,String topic_key,Collection<String> values){
    
            List<Object> objects = stringRedisTemplate.executePipelined(new RedisCallback<Object>() {
                @Nullable
                @Override
                public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                    StringRedisConnection stringRedisConnection = (StringRedisConnection)redisConnection;
                    String[] strings = values.toArray(new String[values.size()]);
                    stringRedisConnection.rPush(topic_key,strings);
                    stringRedisConnection.zRem(future_key,strings);
                    return null;
                }
            });
            return objects;
        }
    
    }

    6.使用:

    实现未来任务分配到zset,现在任务自动进入list

    还需要将任务保存到数据库中

    (1.保存到数据库 2.保存到redis)

    任务取消,如果接口网络不通,使用延迟任务进行重试,当达到阈值后取消任务)

    @Transactional
    @Slf4j
    @Service
    @RequiredArgsConstructor
    public class TaskServiceImpl extends ServiceImpl<TaskinfoMapper, Taskinfo> implements TaskService {
    
    
        private final TaskinfoLogsMapper taskinfoLogsMapper;
        private final TaskinfoMapper taskinfoMapper;
        private final CacheService cacheService;
    
        @Override
        public Long addTask(Task task) {
    //          1.添加任务到数据库表中
            boolean success = addTakeToDb(task);
    
            if (success) {
    //        2.保存数据到redis中
                addTaskToCache(task);
    
            }
    
            return task.getTaskId();
    
        }
    
        private void addTaskToCache(Task task) {
    //        long nextScheduleTime = LocalDateTime.now().plusMinutes(5).atZone(ZoneId.systemDefault())
    //                .toInstant()
    //                .toEpochMilli();
            //        2.保存数据到redis中
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, 5);
            Long nextScheduleTime = calendar.getTimeInMillis();
            if (task.getExecuteTime() <= System.currentTimeMillis()) {
                //        2.1小于当前时间,直接添加到redis的list
                String key = ScheduleConstants.TOPIC + task.getTaskType() + "_" + task.getPriority();
                cacheService.lLeftPush(key, JSON.toJSONString(task));
    
            } else if (task.getExecuteTime() <= nextScheduleTime) {
                //        2.2小于当前时间加上预定时间,添加到zset
                String key = ScheduleConstants.FUTURE + task.getTaskType() + "_" + task.getPriority();
                cacheService.zAdd(key, JSON.toJSONString(task), task.getExecuteTime());
            }
        }
    
        private boolean addTakeToDb(Task task) {
            boolean flag = false;
            try {
    
    //            保存到任务表
                Taskinfo taskinfo = new Taskinfo();
                BeanUtils.copyProperties(task, taskinfo);
                taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
                taskinfoMapper.insert(taskinfo);
    //          保存到任务日志表
                TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
                BeanUtils.copyProperties(taskinfo, taskinfoLogs);
                taskinfoLogs.setExecuteTime(new Date(task.getExecuteTime()));
                taskinfoLogs.setVersion(1);
                taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
                taskinfoLogsMapper.insert(taskinfoLogs);
                task.setTaskId(taskinfo.getTaskId());
                flag = true;
            } catch (BeansException e) {
                e.printStackTrace();
            }
    
    
            return flag;
    
        }
    
        @Override
        public boolean cancelTask(Long taskId) {
    
            boolean flag = false;
    
    
            if (taskId == null)
                return flag;
    //      1.根据d删除任务,并修改任务日志状态
            Task task = updateDb(taskId, ScheduleConstants.CANCELLED);
    //        2.删除redis中的数据
            if (task != null) {
                removeTaskFromCache(task);
                flag = true;
            }
    
            return flag;
    
        }
    
        private void removeTaskFromCache(Task task) {
    
            if (task.getExecuteTime() <= System.currentTimeMillis()) {
                String key = ScheduleConstants.TOPIC + task.getTaskType() + "_" + task.getPriority();
                cacheService.lRemove(key, 0, JSON.toJSONString(task));
            } else {
                String key = ScheduleConstants.FUTURE + task.getTaskType() + "_" + task.getPriority();
                cacheService.zRemove(key, JSON.toJSONString(task));
            }
        }
    
    
        private Task updateDb(Long taskId, int status) {
    
            Task task = new Task();
            try {
    //            删除任务表中的数据
                taskinfoMapper.deleteById(taskId);
                TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
                if (taskinfoLogs != null) {
                    taskinfoLogs.setStatus(status);
                    taskinfoLogsMapper.updateById(taskinfoLogs);
                    BeanUtils.copyProperties(taskinfoLogs, task);
                    task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
                }
            } catch (BeansException e) {
                log.info("Task cancel fail, taskId = {}", taskId);
            }
            return task;
        }
    
        /**
         * 按照任务的类型和优先级拉取任务
         *
         * @param taskType
         * @param priority
         * @return
         */
        @Override
        public Task poll(Integer taskType, Integer priority) {
            if (taskType == null && priority == null) {
                return null;
            }
    
            Task task = new Task();
            String key = ScheduleConstants.TOPIC + taskType + "_" + priority;
            String taskJson = cacheService.lRightPop(key);
            try {
                if (StringUtils.isNotBlank(taskJson)) {
                    task = JSON.parseObject(taskJson, Task.class);
    //                修改数据库信息,updateDb包含了删除任务表和更新任务日志表
                    updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
    
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return task;
        }
    
    
        //    @Scheduled(cron = "*/5 * * * * ?")
        @Scheduled(cron = "0 */1 * * * ?")
        public void refresh() {
            log.info("未来任务定时刷新---定时任务");
    
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {
    //            字符串转换future_10_10变成topic_10_10
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                log.info(topicKey);
    //            查询futurekey中符合要求的数据
    //            借助api拿到在0到当前时间戳,zset中满足sort在这个时间范围内的值
                Set<String> tasks = cacheService.zRange(futureKey, 0, System.currentTimeMillis());
                log.info(tasks.toString());
    //              同步数据,将future_10_10中的数据变成topic_10_10
                if (CollectionUtils.isNotEmpty(tasks)) {
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    log.info("成功的将" + futureKeys + "刷新到了" + topicKey);
                }
            }
        }
    }
    

    总结

    延迟任务的实现方式 DelayQueue,基于JVM

    RabbitMQ:TTL+死信队列(常用)

    Redis:zset特性(常用,本项目实现)

    Logo

    汇聚全球AI编程工具,助力开发者即刻编程。

    更多推荐