为商户添加redis缓存

缓存模型和思路

标准的操作方式就是查询数据库之前先查询缓存,如果缓存数据存在,则直接从缓存中返回,如果缓存数据不存在,再查询数据库,然后将数据存入redis。

 

 代码如下:

 public Result queryById(Long id) {
        //从redis中查询商铺
        String shopStr = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //判断是否命中
        if (StrUtil.isBlank(shopStr) ) {
            Shop  shop = JSONUtil.toBean(shopStr, Shop.class);
            return Result.ok(shop);
        }
        //未命中查询数据库
        Shop  shop = getById(id);
        if (shop==null) {

            return Result.fail("店铺不存在!");
        }
        //将查询到的shop存入Redis, 将shop转化为json
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(shop));

        return Result.ok(shop);
    }

 

posted @ 2022-11-27 10:15  kisshappyboy  阅读(24)  评论(0编辑  收藏  举报