缓存失效问题
先来解决大并发读情况下的缓存失效问题;
1、缓存穿透
 缓存穿透是指查询一个一定不存在的数据,由于缓存是不命中,将去查询数据库,但是数 据库也无此记录,我们没有将这次查询的 null 写入缓存,这将导致这个不存在的数据每次 请求都要到存储层去查询,失去了缓存的意义。
 在流量大时,可能 DB 就挂掉了,要是有人利用不存在的 key 频繁攻击我们的应用,这就是 漏洞。
 解决: 缓存空结果、并且设置短的过期时间。
2、缓存雪崩
 缓存雪崩是指在我们设置缓存时采用了相同的过期时间,导致缓存在某一时刻同时失 效,请求全部转发到 DB,DB 瞬时压力过重雪崩。
 解决:
原有的失效时间基础上增加一个随机值,比如 1-5 分钟随机,这样每一个缓存的过期时间的 重复率就会降低,就很难引发集体失效的事件。
3、缓存击穿
 对于一些设置了过期时间的 key,如果这些 key 可能会在某些时间点被超高并发地访问, 是一种非常“热点”的数据。
 这个时候,需要考虑一个问题:如果这个 key 在大量请求同时进来前正好失效,那么所 有对这个 key 的数据查询都落到 db,我们称为缓存击穿。
 解决: 加锁
分布式锁
1、分布式锁与本地锁

2、分布式锁实现

使用 RedisTemplate 操作分布式锁
抽取业务代码
  
   - 
    
     
    
    
        
      private Map<String, List<Catelog2Vo>> 
      getDataFromDb
      () {
     
    
- 
    
     
    
    
             
      String 
      catalogJSON 
      = redisTemplate.opsForValue().get(
      "catalogJSON");
     
    
- 
    
     
    
    
             
      if (StringUtils.isEmpty(catalogJSON)) {
     
    
- 
    
     
    
    
     
                  Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, 
      new 
      TypeReference<Map<String, List<Catelog2Vo>>>() {
     
    
- 
    
     
    
    
     
                  });
     
    
- 
    
     
    
    
                 
      return result;
     
    
- 
    
     
    
    
     
              }
     
    
- 
    
     
    
    
     
              System.out.println(
      "查询了数据库...");
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
     
              List<CategoryEntity> selectList = baseMapper.selectList(
      null);
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
             
      //1.查出所有一级分类
     
    
- 
    
     
    
    
     
              List<CategoryEntity> level1Categorys = getLevel1Categorys();
     
    
- 
    
     
    
    
             
      //2封装数据
     
    
- 
    
     
    
    
     
              Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
     
    
- 
    
     
    
    
                 
      //1.每一个的一级分类,查到这个一级分类的二级分类
     
    
- 
    
     
    
    
     
                  List<CategoryEntity> categoryEntities = baseMapper.selectList(
      new 
      QueryWrapper<CategoryEntity>()
     
    
- 
    
     
    
    
     
                          .eq(
      "parent_cid", v.getCatId()));
     
    
- 
    
     
    
    
                 
      //2.封装上面的结果
     
    
- 
    
     
    
    
     
                  List<Catelog2Vo> catelog2Vos = 
      null;
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
                 
      if (categoryEntities != 
      null) {
     
    
- 
    
     
    
    
     
                      catelog2Vos = categoryEntities.stream().map(l2 -> {
     
    
- 
    
     
    
    
                         
      Catelog2Vo 
      catelog2Vo 
      = 
      new 
      Catelog2Vo(
     
    
- 
    
     
    
    
     
                                  v.getParentCid().toString(), 
      null, v.getName().toString(), v.getCatId().toString()
     
    
- 
    
     
    
    
     
                          );
     
    
- 
    
     
    
    
                         
      //找出当前二级分类的三级分类分装成vo
     
    
- 
    
     
    
    
     
                          List<CategoryEntity> categoryEntities1 = baseMapper.selectList(
      new 
      QueryWrapper<CategoryEntity>().eq(
      "parent_cid", l2.getCatId()));
     
    
- 
    
     
    
    
     
                          List<Catelog2Vo.Catelog3Vo> collect = 
      null;
     
    
- 
    
     
    
    
                         
      if (categoryEntities1 != 
      null) {
     
    
- 
    
     
    
    
     
                              collect = categoryEntities1.stream().map(l3 -> {
     
    
- 
    
     
    
    
     
                                  Catelog2Vo.
      Catelog3Vo 
      catelog3Vo 
      = 
      new 
      Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getName(), l3.getCatId().toString());
     
    
- 
    
     
    
    
                                 
      return catelog3Vo;
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
     
                              }).collect(Collectors.toList());
     
    
- 
    
     
    
    
     
                          }
     
    
- 
    
     
    
    
     
                          catelog2Vo.setCatalog3List(collect);
     
    
- 
    
     
    
    
                         
      return catelog2Vo;
     
    
- 
    
     
    
    
     
                      }).collect(Collectors.toList());
     
    
- 
    
     
    
    
     
                  }
     
    
- 
    
     
    
    
                 
      return catelog2Vos;
     
    
- 
    
     
    
    
     
              }));
     
    
- 
    
     
    
    
             
      //3.查到的数据再放入缓存中,将对象转为json放进
     
    
- 
    
     
    
    
             
      String 
      s 
      = JSON.toJSONString(parent_cid);
     
    
- 
    
     
    
    
     
              redisTemplate.opsForValue().set(
      "catalogJSON", s);
     
    
- 
    
     
    
    
             
      return parent_cid;
     
    
- 
    
     
    
    
     
          }
     
    
 分布锁情况代码
  
   - 
    
     
    
    
         
      public Map<String, List<Catelog2Vo>> 
      getCatalogJsonForDbWithRedisLock
      () {
     
    
- 
    
     
    
    
             
      //占分布式锁,去redis坑
     
    
- 
    
     
    
    
             
      //设置过期时间 ---2设置过期时间和加锁应为原子性同步
     
    
- 
    
     
    
    
             
      String 
      uuid 
      = UUID.randomUUID().toString();
     
    
- 
    
     
    
    
             
      Boolean 
      lock 
      = redisTemplate.opsForValue().setIfAbsent(
      "lock", uuid,
      30,TimeUnit.SECONDS);
     
    
- 
    
     
    
    
             
      if (lock){
     
    
- 
    
     
    
    
                 
      //加锁成功,执行业务
     
    
- 
    
     
    
    
                 
      //设置过期时间 ---1
     
    
- 
    
     
    
    
     
      // redisTemplate.expire("lock",30, TimeUnit.SECONDS);
     
    
- 
    
     
    
    
     
                  System.out.println(
      "获取分布式锁成功...");
     
    
- 
    
     
    
    
     
                  Map<String, List<Catelog2Vo>> dataFromDb = 
      null;
     
    
- 
    
     
    
    
                 
      try {
     
    
- 
    
     
    
    
     
                      dataFromDb = getDataFromDb();
     
    
- 
    
     
    
    
     
                  }
      finally {
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
                     
      //获取值对比+对比成功删除=》原子操作 lua脚本
     
    
- 
    
     
    
    
                     
      String 
      script 
      = 
      "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
                     
      Integer 
      lock1 
      = redisTemplate.execute(
      new 
      DefaultRedisScript<Integer>(script, Integer.class),
     
    
- 
    
     
    
    
     
                              Arrays.asList(
      "lock"), uuid);
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
                     
      String 
      lockValue 
      = redisTemplate.opsForValue().get(
      "lock");
     
    
- 
    
     
    
    
     
      // if (lockValue.equals(s)){
     
    
- 
    
     
    
    
     
      // redisTemplate.delete("lock");//删除锁
     
    
- 
    
     
    
    
     
      // }
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
     
                  }
     
    
- 
    
     
    
    
                 
      return  dataFromDb;
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
     
              }
      else {
     
    
- 
    
     
    
    
     
                  System.out.println(
      "获取分布式锁失败...等待重试");
     
    
- 
    
     
    
    
                 
      //加锁失败...重试synchronized ()
     
    
- 
    
     
    
    
                 
      //休眠100ms重试
     
    
- 
    
     
    
    
                 
      try {
     
    
- 
    
     
    
    
     
                      Thread.sleep(
      200);
     
    
- 
    
     
    
    
     
                  }
      catch (Exception e){
     
    
- 
    
     
    
    
     
                      System.out.println(e);
     
    
- 
    
     
    
    
     
                  }
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
                 
      return  getCatalogJsonForDbWithRedisLock();
      //自旋
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
     
              }
     
    
- 
    
     
    
    
     
          }
     
    
 //占分布式锁,去redis坑 //设置过期时间 ---设置过期时间和加锁应为原子性同步 Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock",uuid,30,TimeUnit.SECONDS);//获取值对比+对比成功删除=》原子操作 lua脚本lua脚本: String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; 执行脚本 Integer lock1 = redisTemplate.execute(new DefaultRedisScript<Integer>(script, Integer.class), Arrays.asList("lock"), uuid);
本地锁代码
  
   - 
    
     
    
    
      
      /**
     
    
- 
    
     
    
    
     
       * 从数据库查询数据得到数据
     
    
- 
    
     
    
    
     
       * @return
     
    
- 
    
     
    
    
     
       */
     
    
- 
    
     
    
    
         
      public Map<String, List<Catelog2Vo>> 
      getCatalogJsonForDbWithLocalLock
      () {
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
             
      //只要是同一把锁,就能锁住需要这个锁的所有线程
     
    
- 
    
     
    
    
             
      //1.synchronized (this) springboot所有的组件在容器中都是单例的
     
    
- 
    
     
    
    
             
      //todo 本地锁synchronized juc(lock),分布式下应使用分布式锁
     
    
- 
    
     
    
    
             
      synchronized (
      this){
     
    
- 
    
     
    
    
                 
      String 
      catalogJSON 
      = redisTemplate.opsForValue().get(
      "catalogJSON");
     
    
- 
    
     
    
    
                 
      if (StringUtils.isEmpty(catalogJSON)){
     
    
- 
    
     
    
    
     
                      Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, 
      new 
      TypeReference<Map<String, List<Catelog2Vo>>>() {});
     
    
- 
    
     
    
    
                     
      return result;
     
    
- 
    
     
    
    
     
                  }
     
    
- 
    
     
    
    
                 
      /**
     
    
- 
    
     
    
    
     
       * 1.将数据库的数据只查一次
     
    
- 
    
     
    
    
     
       */
     
    
- 
    
     
    
    
     
                  List<CategoryEntity> selectList = baseMapper.selectList(
      null);
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
                 
      //1.查出所有一级分类
     
    
- 
    
     
    
    
     
                  List<CategoryEntity> level1Categorys = getLevel1Categorys();
     
    
- 
    
     
    
    
                 
      //2封装数据
     
    
- 
    
     
    
    
     
                  Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
     
    
- 
    
     
    
    
                     
      //1.每一个的一级分类,查到这个一级分类的二级分类
     
    
- 
    
     
    
    
     
                      List<CategoryEntity> categoryEntities = baseMapper.selectList(
      new 
      QueryWrapper<CategoryEntity>()
     
    
- 
    
     
    
    
     
                              .eq(
      "parent_cid", v.getCatId()));
     
    
- 
    
     
    
    
                     
      //2.封装上面的结果
     
    
- 
    
     
    
    
     
                      List<Catelog2Vo> catelog2Vos = 
      null;
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
                     
      if (categoryEntities != 
      null) {
     
    
- 
    
     
    
    
     
                          catelog2Vos = categoryEntities.stream().map(l2 -> {
     
    
- 
    
     
    
    
                             
      Catelog2Vo 
      catelog2Vo 
      = 
      new 
      Catelog2Vo(
     
    
- 
    
     
    
    
     
                                      v.getParentCid().toString(), 
      null, v.getName().toString(), v.getCatId().toString()
     
    
- 
    
     
    
    
     
                              );
     
    
- 
    
     
    
    
                             
      //找出当前二级分类的三级分类分装成vo
     
    
- 
    
     
    
    
     
                              List<CategoryEntity> categoryEntities1 = baseMapper.selectList(
      new 
      QueryWrapper<CategoryEntity>().eq(
      "parent_cid", l2.getCatId()));
     
    
- 
    
     
    
    
     
                              List<Catelog2Vo.Catelog3Vo> collect=
      null;
     
    
- 
    
     
    
    
                             
      if (categoryEntities1!=
      null){
     
    
- 
    
     
    
    
     
                                  collect = categoryEntities1.stream().map(l3 -> {
     
    
- 
    
     
    
    
     
                                      Catelog2Vo.
      Catelog3Vo 
      catelog3Vo 
      = 
      new 
      Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getName(), l3.getCatId().toString());
     
    
- 
    
     
    
    
                                     
      return catelog3Vo;
     
    
- 
    
     
    
    
      
     
    
- 
    
     
    
    
     
                                  }).collect(Collectors.toList());
     
    
- 
    
     
    
    
     
                              }
     
    
- 
    
     
    
    
     
                              catelog2Vo.setCatalog3List(collect);
     
    
- 
    
     
    
    
                             
      return catelog2Vo;
     
    
- 
    
     
    
    
     
                          }).collect(Collectors.toList());
     
    
- 
    
     
    
    
     
                      }
     
    
- 
    
     
    
    
                     
      return catelog2Vos;
     
    
- 
    
     
    
    
     
                  }));
     
    
- 
    
     
    
    
                 
      //3.查到的数据再放入缓存中,将对象转为json放进
     
    
- 
    
     
    
    
                 
      String 
      s 
      = JSON.toJSONString(parent_cid);
     
    
- 
    
     
    
    
     
                  redisTemplate.opsForValue().set(
      "catalogJSON",s);
     
    
- 
    
     
    
    
                 
      return  parent_cid;
     
    
- 
    
     
    
    
     
              }
     
    
- 
    
     
    
    
     
          }
     
    
 //只要是同一把锁,就能锁住需要这个锁的所有线程
//1.synchronized (this) springboot所有的组件在容器中都是单例的//3.查到的数据再放入缓存中,将对象转为json放进
转载:https://blog.csdn.net/m0_62436868/article/details/128759692
查看评论
					 
					