栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

StringRedisTemplate与RedisTemplate的区别,以及Redis的工具类封装

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

StringRedisTemplate与RedisTemplate的区别,以及Redis的工具类封装

StringRedisTemplate与RedisTemplate区别点

  • 两者的关系是StringRedisTemplate继承RedisTemplate。
  • 两者的数据是不共通的;也就是说StringRedisTemplate只能管理StringRedisTemplate里面的数据,RedisTemplate只能管理RedisTemplate中的数据。
  • RedisTemplate使用的是JdkSerializationRedisSerializer序列化类,存入数据会将数据先序列化成字节数组然后在存入Redis数据库。 StringRedisTemplate使用的是StringRedisSerializer序列化类
  • 当redis数据库里面本来存的是字符串数据或者要存取的数据就是字符串类型数据的时候,那么使用StringRedisTemplate即可。但是如果你的数据是复杂的对象类型,而取出的时候又不想做任何的数据转换,直接从Redis里面取出一个对象,那么使用RedisTemplate是更好的选择。
  • redisTemplate 中存取数据都是字节数组。当redis中存入的数据是可读形式而非字节数组时,使用redisTemplate取值的时候会无法获取导出数据,获得的值为null。可以使用 StringRedisTemplate 试试

RedisTemplate中定义了5种数据结构操作:

redisTemplate.opsForValue();  //操作字符串
redisTemplate.opsForHash();   //操作hash
redisTemplate.opsForList();   //操作list
redisTemplate.opsForSet();    //操作set
redisTemplate.opsForZSet();   //操作有序set

StringRedisTemplate常用操作

// 向redis里存入数据和设置缓存时间  
stringRedisTemplate.opsForValue().set("test", "100", 60*10, TimeUnit.SECONDS);

// val做-1操作
stringRedisTemplate.boundValueOps("test").increment(-1); 

// 根据key获取缓存中的val
stringRedisTemplate.opsForValue().get("test") 

// val + 1
stringRedisTemplate.boundValueOps("test").increment(1); 

// 根据key获取过期时间
stringRedisTemplate.getExpire("test") 

// 根据key获取过期时间并换算成指定单位 
stringRedisTemplate.getExpire("test",TimeUnit.SECONDS); 

// 根据key删除缓存
stringRedisTemplate.delete("test"); 

// 检查key是否存在,返回boolean值
stringRedisTemplate.hasKey("546545");  

// 向指定key中存放set集合
stringRedisTemplate.opsForSet().add("red_123`在这里插入代码片`", "1", "2", "3"); 

// 设置过期时间
stringRedisTemplate.expire("red_123", 1000 , TimeUnit.MILLISECONDS); 

// 根据key查看集合中是否存在指定数据
stringRedisTemplate.opsForSet().isMember("red_123", "1"); 

// 根据key获取set集合
stringRedisTemplate.opsForSet().members("red_123"); 

基于StringRedisTemplate封装一个缓存工具类,满足下列需求:

  • 方法1:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置TTL过期时间
  • 方法2:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置逻辑过期时间,用于处理缓存击穿问题
  • 方法3:根据指定的key查询缓存,并反序列化为指定类型,利用缓存空值的方式解决缓存穿透问题
  • 方法4:根据指定的key查询缓存,并反序列化为指定类型,需要利用逻辑过期解决缓存击穿问题

以下封装涉及到了缓存穿透与缓存击穿的解决方案,如果对两者不熟悉,可以看看我的另一篇博客了解一下这些解决方案:数据库面试题——redis缓存穿透、缓存击穿与缓存雪崩

依赖:

        
            cn.hutool
            hutool-all
            5.7.17
        

封装:

@Component
@Slf4j
public class RedisUtils {

    @Autowired
    private static RedisTemplate redisTemplate;

    private final StringRedisTemplate stringRedisTemplate;

    // 防止缓存穿透而设置的空值的过期时间
    private final Long CACHE_NULL_TTL = 2L;

    // 防止缓存穿透而设置的空值的过期时间的单位
    private final TimeUnit CACHE_UNIT = TimeUnit.MINUTES;

    // 互斥锁
    private final String LOCK_APP_KEY = "lock:app:";

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public RedisUtils(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    // =============================common============================

    
    public boolean expire(String key, long time) {
        if (time <= 0) return false;
        redisTemplate.expire(key, time, TimeUnit.SECONDS);
        return true;
    }

    
    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    
    public Long getExpire(String key, TimeUnit unit) {
        return redisTemplate.getExpire(key, unit);
    }

    
    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    
    public boolean del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(Arrays.asList(key));
            }
            return true;
        }
        return false;
    }

    
    public boolean DelByPrefix(String prefix) {
        Set keys = redisTemplate.keys(prefix + "*");
        if(Objects.nonNull(keys)) {
            redisTemplate.delete(keys);
            return true;
        }
        return false;
    }

    // ============================String=============================

    
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error("缓存写入错误!key:{},value:{},错误信息:{}", key, value, e.getMessage());
            return false;
        }
    }

    
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error("缓存写入错误!key:{},value:{},time:{},错误信息:{}", key, value, time, e.getMessage());
            return false;
        }
    }

    
    public Long incr(String key) {
        return redisTemplate.opsForValue().increment(key, 1);
    }

    
    public Long incr(String key, long step) {
        return redisTemplate.opsForValue().increment(key, step);
    }

    
    public Long decr(String key) {
        return redisTemplate.opsForValue().increment(key, -1);
    }

    
    public Long decr(String key, long step) {
        return redisTemplate.opsForValue().increment(key, -step);
    }

    // ================================Map=================================

    
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    
    public Map hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    
    public boolean hmset(String key, Map map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    public boolean hmset(String key, Map map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("HashSet写入错误!key:{},map:{},time:{},错误信息:{}", key, map, time, e.getMessage());
            return false;
        }
    }

    
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            log.error("hset写入错误!key:{},item:{},value:{},错误信息:{}", key, item, value, e.getMessage());
            return false;
        }
    }

    
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("hset写入错误!key:{},item:{},value:{},time:{},错误信息:{}", key, item, value, time, e.getMessage());
            return false;
        }
    }

    
    public boolean hdel(String key, Object... item) {
        try {
            redisTemplate.opsForHash().delete(key, item);
            return true;
        } catch (Exception e) {
            log.error("hdel删除错误!key:{},item:{},错误信息:{}", key, item, e.getMessage());
            return false;
        }
    }

    
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    
    public double hincr(String key, String item, double step) {
        return redisTemplate.opsForHash().increment(key, item, step);
    }

    
    public double hdecr(String key, String item, double step) {
        return redisTemplate.opsForHash().increment(key, item, -step);
    }

    // ============================set=============================

    
    public Set sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            log.error("sGet获取错误!key:{},错误信息:{}", key, e.getMessage());
            return null;
        }
    }

    
    public boolean sHasKey(String key, Object value) {
        try {
            return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, value));
        } catch (Exception e) {
            log.error("sHasKey查询错误!key:{},value:{},错误信息:{}", key, value, e.getMessage());
            return false;
        }
    }

    
    public Long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            log.error("sSet写入错误!key:{},values:{},错误信息:{}", key, values, e.getMessage());
            return null;
        }
    }

    
    public Long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) expire(key, time);
            return count;
        } catch (Exception e) {
            log.error("sSet写入错误!key:{},time:{},values:{},错误信息:{}", key, time, values, e.getMessage());
            return null;
        }
    }

    
    public Long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            log.error("sGetSetSize获取错误!key:{},错误信息:{}", key, e.getMessage());
            return null;
        }
    }

    
    public Long setRemove(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().remove(key, values);
        } catch (Exception e) {
            log.error("setRemove移除错误!key:{},values:{},错误信息:{}", key, values, e.getMessage());
            return null;
        }
    }

    // ===============================list=================================

    
    public List lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            log.error("lGet获取错误!key:{},start:{},end:{},错误信息:{}", key, start, end, e.getMessage());
            return null;
        }
    }

    
    public Long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            log.error("lGetListSize获取错误!key:{},错误信息:{}", key, e.getMessage());
            return null;
        }
    }

    
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            log.error("lGetIndex获取错误!key:{},index:{},错误信息:{}", key, index, e.getMessage());
            return null;
        }
    }

    
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            log.error("lSet写入错误!key:{},value:{},错误信息:{}", key, value, e.getMessage());
            return false;
        }
    }

    
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            log.error("lSet写入错误!key:{},value:{},time:{},错误信息:{}", key, value, time, e.getMessage());
            return false;
        }
    }

    
    public boolean lSet(String key, List value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            log.error("lSet写入错误!key:{},value:{},错误信息:{}", key, value, e.getMessage());
            return false;
        }
    }

    
    public boolean lSet(String key, List value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            log.error("lSet写入错误!key:{},value:{},time:{},错误信息:{}", key, value, time, e.getMessage());
            return false;
        }
    }

    
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            log.error("lUpdateIndex更新错误!key:{},index:{},value:{},错误信息:{}", key, index, value, e.getMessage());
            return false;
        }
    }

    
    public Long lRemove(String key, long count, Object value) {
        try {
            return redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception e) {
            log.error("lRemove移除错误!key:{},count:{},value:{},错误信息:{}", key, count, value, e.getMessage());
            return null;
        }
    }

    public void setString(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    
    public  R getWithPassThrough(
            String keyPrefix,
            ID id,
            Class type,
            Function dbFallback,
            Long time,
            TimeUnit unit
    ){
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        if (json != null) {
            return null;
        }
        // id不存在,去数据库查询
        R r = dbFallback.apply(id);
        if (r == null) {
            // 数据不存在,则存空值,防止缓存穿透
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, CACHE_UNIT);
            return null;
        }
        // 数据存在,则写入缓存
        this.setString(key, r, time, unit);
        return r;
    }

    
    public  R getWithLogicalExpire(
            String keyPrefix,
            ID id,
            Class type,
            Function dbFallback,
            Long time,
            TimeUnit unit
    ) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(json)) {
            return null;
        }
        // 命中,需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        if(expireTime.isAfter(LocalDateTime.now())) {
            // 未过期,直接返回信息
            return r;
        }
        // 缓存重建,获取互斥锁
        String lockKey = LOCK_APP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock){
            // 成功获取锁,开启独立线程,实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R newR = dbFallback.apply(id);
                    this.setWithLogicalExpire(key, newR, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    unlock(lockKey);
                }
            });
        }
        return r;
    }

    
    public  R getWithMutex(
            String keyPrefix,
            ID id,
            Class type,
            Function dbFallback,
            Long time,
            TimeUnit unit
    ) {
        String key = keyPrefix + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {
            return JSONUtil.toBean(shopJson, type);
        }
        if (shopJson != null) {
            return null;
        }

        // 实现缓存重建,获取互斥锁
        String lockKey = LOCK_APP_KEY + id;
        R r = null;
        try {
            boolean isLock = tryLock(lockKey);
            if (!isLock) {
                // 获取锁失败,休眠并重试
                Thread.sleep(50);
                return getWithMutex(keyPrefix, id, type, dbFallback, time, unit);
            }
            // 获取锁成功,根据id查询数据库
            r = dbFallback.apply(id);
            if (r == null) {
                // 将空值写入redis
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 存在则写入redis
            this.setString(key, r, time, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            unlock(lockKey);
        }
        return r;
    }

    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}

 

如果有兴趣了解更多相关内容,欢迎来我的个人网站看看:瞳孔的个人空间

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号