11.29_黑马Redis实战篇商户查询缓存

实战篇1

实战篇2

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryById(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //1,从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2,判断是否存在
        if(StrUtil.isNotBlank(shopJson)){
        //3,存在,直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        //4,不存在,根据id查询数据库
        Shop shop = getById(id);
        //5,不存在,返回错误
        if(shop == null){
            return Result.fail("店铺不存在!");
        }
        //6,存在,写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop));
        //7,返回
        return null;
    }

实战篇4

操作缓存用时较短,操作数据库用时较长

实战篇5

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryById(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //1,从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2,判断是否存在
        if(StrUtil.isNotBlank(shopJson)){
        //3,存在,直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        //4,不存在,根据id查询数据库
        Shop shop = getById(id);
        //5,不存在,返回错误
        if(shop == null){
            return Result.fail("店铺不存在!");
        }
        //6,存在,写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //7,返回
        return null;
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if(id==null){
            return Result.fail("店铺id不能为空");
        }
        //1,更新数据库
        updateById(shop);
        //2,删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
        return Result.ok();
    }
}

做了以下改进:

1,在查询操作的时候,设置了过期时间。

2,在更新操作的时候,先更新数据库,后删除缓存。

实战篇6

危害:对数据库造成巨大压力

细节:

针对缓存空对象方案:

1,针对额外的内存消耗多现象,解决方案:定时清理缓存,设置ttl

2,针对短期不一致现象,解决方案:设置更精细的ttl

实战篇7

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryById(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //1,从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2,判断是否存在
        if(StrUtil.isNotBlank(shopJson)){
        //3,存在,直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        //判断命中的是否是空值
        if(shopJson != null){
            //返回一个错误信息
            return  Result.fail("店铺信息不存在!");
        }

        //4,不存在,根据id查询数据库
        Shop shop = getById(id);
        //5,不存在,返回错误
        if(shop == null){
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            //返回错误信息
            return Result.fail("店铺不存在!");
        }
        //6,存在,写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //7,返回
        return Result.ok(shop) ;
    }

上一篇这里的 return 忘记改回Result.ok(shop)了

实战篇8

实战篇9

前者选择了一致性 

后者选择了可用性

实战篇10

bug1:redis和我的idea连接不上。

天啊,我竟然以最短的时间解决了一个bug!!!!!!!!!

具体问题如下:

怀疑问题所在:之前做苍穹的时候,和我的redis的连接池连接了,因为我发现我的db01有苍穹的数据,然后没有办法连接我的黑马点评,但是我不知道该怎么取消那个连接。于是我删除了redis的软件,以及快捷软件。

这个不需要太多的操作,不需要配置环境变量。

如果不把红色软件重新下载,有可能出现以上bug 

具体解决步骤:

1,直接按删除卸载完,在黑马JAVAWEB2023day5重新下载这两个东西。

2,在下面这个文件下打开cmd

3,输入以下代码

先打开一个cmd输入: redis-ser 用tab补充完整  redis.wind 用tab补充完整

再打开另一个cmd输入:redis-cli 用tab补充完整

注意:两个cmd都要在,不可以删除其中一个。

 4(可能不需要),打开服务,启动

就算不启动也可以,但是我上一次处理redis的bug的时候需要启动的,反正都试试。

5(上次bug试过,可以的)如果还不行试试开启全部权限。

6,最后检查host有没有写错,port有没有写错  要一一对应

是可以不设置密码的,也可以不指定database

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

 public Result queryById(Long id) {
        //缓存穿透
        //Shop shop = queryWithPassThrough(id);
        //互斥锁解决缓存穿透
        Shop shop =queryWithMutex(id);
        if(shop == null){
            return Result.fail("店铺不存在!");
        }
        //7,返回
        return Result.ok(shop);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        //1,更新数据库
        updateById(shop);
        //2,删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1,从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2,判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3,存在,直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //判断命中的是否是空值
        if (shopJson != null) {
            //返回一个错误信息
            return null;
        }

        //4,不存在,根据id查询数据库
        Shop shop = getById(id);
        //5,不存在,返回错误
        if (shop == null) {
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //返回错误信息
            return null;
        }
        //6,存在,写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //7,返回
        return shop;
    }

    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1,从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2,判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3,存在,直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //判断命中的是否是空值
        if (shopJson != null) {
            //返回一个错误信息
            return null;
        }
        //4,实现缓存重建
        //4.1 获取互斥锁
        String lockkey = "lock:shop:" + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockkey);
            //4.2 判断是否获取成功
            if (!isLock) {
                //4.3 失败,则休眠并重试
                Thread.sleep(50);
                queryWithMutex(id);
            }
            //4.4,成功,根据id查询数据库
            shop = getById(id);
            //因为这个系统是在本地的,操作速度非常快,因此,模拟重建的延时
            Thread.sleep(200);
            //5,不存在,返回错误
            if (shop == null) {
                //将空值写入redis
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                //返回错误信息
                return null;
            }
            //6,存在,写入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            //这个打断的异常,直接抛出即可以,不用处理
            throw new RuntimeException (e);
        }
        //7,释放互斥锁
            unlock(lockkey);
            //8,返回
            return shop;


    }

    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);
    }
}

实战篇11

thinking:Json Bean这些到底是什么?有什么用处?

Hutool参考文档

 

 JSON 基本使用_json怎么用-CSDN博客

 

thinking:JSON序列化和反序列化?

JSON序列化和反序列化_json反序列化_好奇的mao的博客-CSDN博客

 thinking:JSONOBJECT是什么?

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        //缓存穿透
        //Shop shop = queryWithPassThrough(id);
        //互斥锁解决缓存穿透
        //Shop shop =queryWithMutex(id);
        //逻辑过期解决缓存穿透
        Shop shop = queryWithLoginExpire(id);
        if (shop == null) {
            return Result.fail("店铺不存在!");
        }
        //7,返回
        return Result.ok(shop);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }
        //1,更新数据库
        updateById(shop);
        //2,删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1,从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2,判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3,存在,直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //判断命中的是否是空值
        if (shopJson != null) {
            //返回一个错误信息
            return null;
        }

        //4,不存在,根据id查询数据库
        Shop shop = getById(id);
        //5,不存在,返回错误
        if (shop == null) {
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //返回错误信息
            return null;
        }
        //6,存在,写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //7,返回
        return shop;
    }

    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1,从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2,判断是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3,存在,直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        //判断命中的是否是空值
        if (shopJson != null) {
            //返回一个错误信息
            return null;
        }
        //4,实现缓存重建
        //4.1 获取互斥锁
        String lockkey = "lock:shop:" + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockkey);
            //4.2 判断是否获取成功
            if (!isLock) {
                //4.3 失败,则休眠并重试
                Thread.sleep(50);
                queryWithMutex(id);
            }
            //4.4,成功,根据id查询数据库
            shop = getById(id);
            //因为这个系统是在本地的,操作速度非常快,因此,模拟重建的延时
            Thread.sleep(200);
            //5,不存在,返回错误
            if (shop == null) {
                //将空值写入redis
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                //返回错误信息
                return null;
            }
            //6,存在,写入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            //这个打断的异常,直接抛出即可以,不用处理
            throw new RuntimeException(e);
        }
        //7,释放互斥锁
        unlock(lockkey);
        //8,返回
        return shop;


    }


    public Shop queryWithLoginExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1,从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2,判断是否存在
        if (StrUtil.isBlank(shopJson)) {
            //3,存在,直接返回
            return null;
        }
        //4,命中,需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5,判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.1 未过期,直接返回店铺信息
            return shop;
        }
        //5.2已过期,需要缓存重建
        //6.缓存重建
        //6.1,获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //6.2,判断是否获取锁成功
        if (isLock) {
            //6.3 成功,开启独立线程,实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //重建缓存
                    //实际上要写30分钟
                    this.saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                //释放锁
                unlock(lockKey);
            });
        }
            //6.4 返回过期的商铺信息
            //6.5 不存在,根据id查询数据库

            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return shop;
        }




    //建立池子
    private  static  final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
        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);
    }

    public  void saveShop2Redis(Long id,Long expireSeconds){
        //1,查询店铺数据
        Shop shop = getById(id);
        //2,封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3,写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }
}

实战篇12

方法一和方法三 针对普通的问题

实战篇12的工具封装代码单独发一篇文章

  • 42
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值