黑马点评给查询商铺的缓存添加超时剔除和主动更新策略

文章目录

      • 1.更新数据库,删除缓存

1.更新数据库,删除缓存

更新操作

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

查询操作

    @Override
    public Result queryById(Long id) {
        String key = CACHE_SHOP_KEY+id;
        // 1.从redis中查询店铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 2.判断缓存是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        // 3.不存在,根据id查询数据库
        Shop shop = getById(id); // mybatisplus功能
        // 4.不存在,返回错误
        if (shop == null) {
            return Result.fail("店铺数据不存在");
        }
        // 存在,写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

添加超时剔除时间30Min

你可能感兴趣的:(缓存,spring,mybatis,spring,boot,java,redis)