代码如下:
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryShopType() {
String key = CACHE_SHOP_TYPE_KEY;
//1、从Redis中查询店铺类型
String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
//2、判断是否存在
if(StrUtil.isNotBlank(shopTypeJson)){
//3、存在,直接返回
List<ShopType> shopTypeList = JSONUtil.toList(shopTypeJson, ShopType.class);
return Result.ok(shopTypeList);
}
//4、不存在,从数据库中查询
List<ShopType> typeList = query().orderByAsc("sort").list();
//5、不存在,返回错误
if(typeList == null || typeList.isEmpty()){
return Result.fail("店铺类型查询失败!");
}
//6、存在,写入Redis缓存
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(typeList));
//7、返回结果
return Result.ok(typeList);
}
}