给商铺类型查询业务添加缓存
黑马点评P37集,给商铺类型业务添加缓存。
商铺类型是list类型,较36集需要一些改动。
ShopTypeController
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
@Resource
private IShopTypeService typeService;
@GetMapping("list")
public Result queryTypeList() {
return typeService.queryList();
}
}
ShopTypeService
public interface IShopTypeService extends IService<ShopType> {
Result queryList();
}
ShopTypeServiceImpl
// 自定义常量
public static final String CACHE_TYPE_LIST = "cache:type:";
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryList() {
String key = CACHE_TYPE_LIST;
// 1.从redis查询商户类型缓存
String typeJson = stringRedisTemplate.opsForValue().get(key);
// 2.判断是否存在
if (StrUtil.isNotBlank(typeJson)) {
// 3.存在直接返回
List<ShopType> shopTypeList = JSONUtil.toList(typeJson, ShopType.class);
return Result.ok(shopTypeList);
}
// 4.不存在,根据商户类型id查询数据库
List<ShopType> shopTypeList = query().orderByAsc("sort").list();
// 5.存在,写入redis
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypeList));
// 6.返回
return Result.ok(shopTypeList);
}
}