黑马点评给店铺类型查询业务添加缓存(List实现)

代码如下:

    public Result queryShopTypeList() {
        String key = CACHE_SHOP_TYPE_KEY_List;
        //1、从Redis中查询店铺类型,获取所有
        List<String> shopTypeList = stringRedisTemplate.opsForList().range(key, 0, -1);
        //2、判断是否存在
        if(!shopTypeList.isEmpty()){
            //3、存在,直接返回
            //转换成ShopType类型的list
            List<ShopType> typeList = new ArrayList<>();
            for(String s: shopTypeList){
                ShopType shopType = JSONUtil.toBean(s, ShopType.class);
                typeList.add(shopType);
            }
            return Result.ok(typeList);
        }
        //4、不存在,从数据库中查询
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //5、不存在,返回错误
        if(typeList == null || typeList.isEmpty()){
            return Result.fail("店铺类型查询失败!");
        }
        //6、存在,写入Redis缓存
        //将ShopType转换成String类型的list
        for(ShopType shopType: typeList){
            shopTypeList.add(JSONUtil.toJsonStr(shopType));
        }
        stringRedisTemplate.opsForList().rightPushAll(key, shopTypeList);
        //7、返回结果
        return Result.ok(typeList);
    }

你可能感兴趣的:(Redis,黑马点评,缓存,java,redis)