controller/ShopTypeController.java
/*** 店铺分类查询,用于展示首页头部店铺分类* @return*/@GetMapping("list")public Result queryTypeList() {return typeService.queryList();}
service/IShopTypeService.java
Result queryList();
service/impl/ShopTypeServiceImpl.java
@Autowiredprivate StringRedisTemplate redisTemplate;@Overridepublic Result queryList() {//使用list取 [0 -1] 代表全部//从redis中查询所有分类List<String> shopTypeList = redisTemplate.opsForList().range(SHOP_LIST_KEY, 0, -1);if (CollectionUtil.isNotEmpty(shopTypeList)) {//shopTypeList.get(0) 其实是获取了整个List集合里的元素,0是第0个key//查询到,直接返回List<ShopType> types = JSONUtil.toList(shopTypeList.get(0), ShopType.class);return Result.ok(types);}/* //使用string 取String shopType = redisTemplate.opsForValue().get(SHOP_LIST_KEY);if (!StrUtil.isEmpty(shopType)){List<ShopType> types= JSONUtil.toList(shopType, ShopType.class);return Result.ok(types);}*///redis中没有,查询数据库List<ShopType> typeList = query().orderByAsc("sort").list();//数据库中没有,报错if (CollectionUtil.isEmpty(typeList)) {return Result.fail("列表信息不存在");}//list 存//数据库中有,存到redis,注意存的位置和上面取的位置一致。String jsonStr = JSONUtil.toJsonStr(typeList);redisTemplate.opsForList().leftPushAll(SHOP_LIST_KEY, jsonStr);return Result.ok(typeList);/* //string 存redisTemplate.opsForValue().set(SHOP_LIST_KEY,JSONUtil.toJsonStr(typeList);*/}
运行,redis数据库中出现数据如下,测试成功。