• 仿黑马点评-redis整合【三、缓存工具封装】


    前言
    👏作者简介:我是笑霸final,一名热爱技术的在校学生。
    📝个人主页:个人主页1 || 笑霸final的主页2
    📕系列专栏:《项目专栏》
    📧如果文章知识点有错误的地方,请指正!和大家一起学习,一起进步👀
    🔥如果感觉博主的文章还不错的话,👍点赞👍 + 👀关注👀 + 🤏收藏🤏

    在这里插入图片描述

    案列

    上节回顾 仿黑马点评-redis整合【二——商户查询缓存】——缓存穿透、缓存击穿的解决

    在这里插入图片描述一些工具代码

      //设置锁
        private boolean tryLock(String key) {
            //我们利用redis中的 setnx
            Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
            return BooleanUtil.isTrue(flag);
        }
    
        //释放锁
        private void unlock(String key) {
            stringRedisTemplate.delete(key);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    方法一set

    • 先写工具
      在这里插入图片描述

    在这里插入图片描述我们需要json字符串,用hutool工具包的方法在这里插入图片描述

    • 代码
     //方法一
        public void set(String key, Object value, Long time, TimeUnit unit){
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
        }
    
    • 1
    • 2
    • 3
    • 4

    方法二 setWithLogicalExpire

    在这里插入图片描述

    逻辑过期:存数据的时候,给数据加上逻辑过期的字段

     //方法二
        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)));//过期时间
            //写入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    方法三 queryWithPassThrough

    在这里插入图片描述

    public <R,ID> R queryWithPassThrough(
                String keyPrefix,
                ID id,
                Class<R> type,
                Function<ID, R> dbFallback,
                Long time,
                TimeUnit unit
                ){
            String key = keyPrefix + id;
            // 1.从redis查询商铺缓存
            String json = stringRedisTemplate.opsForValue().get(key);
            // 2.判断是否存在
            if (StrUtil.isNotBlank(json)) {
                // 3.存在,直接返回
                return JSONUtil.toBean(json, type);
            }
            // 判断命中的是否是空值
            if (json != null) {
                // 返回一个错误信息
                return null;
            }
    
            // 4.不存在,根据id查询数据库
            R r = dbFallback.apply(id);
            // 5.不存在,返回错误
            if (r == null) {
                // 将空值写入redis
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                // 返回错误信息
                return null;
            }
            // 6.存在,写入redis
            this.set(key, r, time, unit);
            return r;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    在ShopServiceImpl改造

     @Override
        public Result queryById(Long id) {
        Shop shop = cacheClient.queryWithPassThrough(
                    CACHE_SHOP_KEY,
                    id, Shop.class,
                    this::getById,
                    60l, TimeUnit.MINUTES);
    
            if (shop==null){
                return Result.fail("店铺不存在");
            }
            return Result.ok(shop);
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    方法四 queryWithLogicalExpire

    在这里插入图片描述

    //方法四
        public <R, ID> R queryWithLogicalExpire(
                String keyPrefix, ID id,
                Class<R> type,
                Function<ID, R> dbFallback,
                Long time, TimeUnit unit) {
    
            String key = keyPrefix + id;
            // 1.从redis查询商铺缓存
            String json = stringRedisTemplate.opsForValue().get(key);
            // 2.判断是否存在
            if (StrUtil.isBlank(json)) {
                // 3.存在,直接返回
                return null;
            }
            // 4.命中,需要先把json反序列化为对象
            RedisData redisData = JSONUtil.toBean(json, RedisData.class);
            R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
            LocalDateTime expireTime = redisData.getExpireTime();
            // 5.判断是否过期
            if(expireTime.isAfter(LocalDateTime.now())) {
                // 5.1.未过期,直接返回店铺信息
                return r;
            }
            // 5.2.已过期,需要缓存重建
            // 6.缓存重建
            // 6.1.获取互斥锁
            String lockKey = LOCK_SHOP_KEY + id;
            boolean isLock = tryLock(lockKey);
            // 6.2.判断是否获取锁成功
            if (isLock){
                // 6.3.成功,开启独立线程,实现缓存重建
                ExcutorService_CACHE_RECUTOR.submit(() -> {
                    try {
                        // 查询数据库
                        R newR = dbFallback.apply(id);
                        // 重建缓存
                        this.setWithLogicalExpire(key, newR, time, unit);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }finally {
                        // 释放锁
                        unlock(lockKey);
                    }
                });
            }
            // 6.4.返回过期的商铺信息
            return r;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
  • 相关阅读:
    【基础篇】三、SpringBoot基础配置
    Linux 信号
    Kubernetes Pod自动扩容和缩容 基于自定义指标
    机器学习 - 平均中位数模式——python
    前端学习C语言 - 第二篇(常量、运算符、控制和循环)
    Java 快速入门
    SpringBoot粗浅分析
    javascript错误处理和调试工具
    Java 不同接口中含有相同签名方法
    Kafka关键点总结-消息的顺序性
  • 原文地址:https://blog.csdn.net/weixin_52062043/article/details/127727531