redis之:查询缓存

添加缓存:

//添加商户缓存
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        //1.从redis中查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
        //2.判断是否存在
//        isNotBlank不为空,包括""和null
        if (StrUtil.isNotBlank(shopJson)) {
            //3.存在则直接返回信息
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        //防止缓存穿透
        if ("".equals(shopJson)) {
            return Result.fail("店铺不存在");
        }
        //4.不存在,查询数据库
        Shop shop = getById(id);
        //5.数据库中数据不存在,返回错误信息
        if (shop == null) {
            //在redis中设置空值,防止缓存穿透
            stringRedisTemplate.opsForValue().set("cache:shop:" +
id,"",2,TimeUnit.MINUTES);
            return Result.fail("数据不存在");
        }
        //6.存在写入redis,返回信息
        stringRedisTemplate.opsForValue().set("cache:shop:"+id,JSONUtil.toJsonStr(shop),30L,TimeUnit.MINUTES);
        return Result.ok(shop);
    }
}

 更新缓存 :

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @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:"+id);
        return Result.ok();
    }
}

缓存雪崩:

缓存击穿:

 

互斥锁解决缓存击穿

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        Shop shop = queryWithMutex(id);
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    //尝试获取锁的方法
    private Boolean tryLock(String lockKey) {
        //一般比正常业务时间长一点
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", 10, TimeUnit.SECONDS);
        //不能直接返回flag,会做拆箱的,可能会出现空指针
        return BooleanUtil.isTrue(flag);
    }

    //释放锁方法
    private void unLock(String lockKey) {
        stringRedisTemplate.delete(lockKey);
    }

    //防止缓存击穿
    public Shop queryWithMutex(Long id) {
        //1.从redis中查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
        //2.判断是否存在
//        isNotBlank不为空,包括""和null
        if (StrUtil.isNotBlank(shopJson)) {
            //3.存在则直接返回信息
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //防止缓存穿透
        if ("".equals(shopJson)) {
            return null;
        }
        //4.实现缓存重建
        //4.1获取互斥锁
        String lockKey = "lock:shop:" + id;
        Shop shop = null;
        try {
            Boolean lock = tryLock(lockKey);
            //4.2判断获取锁是否成功
            if (!lock) {
                //4.3不成功,休眠并重试
                Thread.sleep(50);
                queryWithMutex(id);
            }
            //5.查询数据库
            shop = getById(id);
            //6.数据库中数据不存在,返回错误信息
            if (shop == null) {
                //在redis中设置空值,防止缓存穿透
                stringRedisTemplate.opsForValue().set("cache:shop:" + id, "", 2, TimeUnit.MINUTES);
                return null;
            }
            //7.存在写入redis,返回信息
            stringRedisTemplate.opsForValue().set("cache:shop:" + id, JSONUtil.toJsonStr(shop), 30L, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //8.释放互斥锁
            unLock(lockKey);
        }
        //9.返回
        return shop;
    }
}

 逻辑过期解决缓存击穿

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //缓存池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) {
        //1.从redis查询商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get("cache:shop:" + id);
        //2.判断是否存在
        if (StrUtil.isBlank(shopJson)) {
            //3.存在,直接返回null
            return null;
        }
        //4.命中,把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        //5.判断是否过期
        LocalDateTime expireTime = redisData.getExpireTime();
        //过期时间是否在当前时间之后,如果在,就未过期;反正,过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.1.未过期,返回店铺信息
            return Result.ok(shop);
        }
        //5.2.已过期,需要缓存重建
        //6.缓存重建
        //6.1.获取互斥锁
        String lockKey = "lock:shop:" + id;
        //6.2.判断获取锁是否成功
        if (tryLock(lockKey)) {
            //6.3.成功,开启独立线程,实现缓存重建(线程池做)
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //重建缓存
                    this.saveShopToRedis(id,1800L);
                } catch (Exception e) {
                        throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unLock(lockKey);
                }
            });
        }
        //6.4.返回过期的商铺信息
        return Result.ok(shop);
    }

 //尝试获取锁的方法
    private Boolean tryLock(String lockKey) {
        //一般比正常业务时间长一点
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", 10, TimeUnit.SECONDS);
        //不能直接返回flag,会做拆箱的,可能会出现空指针
        return BooleanUtil.isTrue(flag);
    }

    //释放锁方法
    private void unLock(String lockKey) {
        stringRedisTemplate.delete(lockKey);
    }

public void saveShopToRedis(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));
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值