当前位置: 首页 > article >正文

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的工具封装代码单独发一篇文章


http://www.kler.cn/a/152828.html

相关文章:

  • android 动态创建selector状态选择器 动态创建Drawable
  • redis集群模式
  • 带头结点的双向循环链表
  • WordPress插件大全-免费的WordPress插件汇总
  • 浏览器安全攻击与防御
  • 重生之我是一名程序员 47 ——字符串函数 (6)
  • uniapp微信小程序实现地图展示控件
  • 【Java】文件I/O-文件内容操作-输入输出流-Reader/Writer/InputStream/OutputStream四种流
  • 苍穹外卖项目笔记(5)——Redis
  • Python函数关键字参数及用法
  • Spring简单的存储和读取
  • 【蓝桥杯选拔赛真题25】C++两个数比大小 第十三届蓝桥杯青少年创意编程大赛C++编程选拔赛真题解析
  • 数字电源为什么一般用DSP控制,而不能用普通的单片机?
  • OpenStack-train版安装之安装Keystone(认证服务)、Glance(镜像服务)、Placement
  • Scan Context / Scan Context ++ 论文和源码阅读
  • 西南科技大学模拟电子技术实验一(常用电子仪器的使用及电子元器件的识别)预习报告
  • C++相关闲碎记录(2)
  • ubuntu离线安装包下载和安装
  • Linux安全配置
  • Windows核心编程 远程线程注入