Controller → Service(接口) → ServiceImpl(实现类,写缓存)
1.list缓存
@RestController @RequestMapping("/shop-type") public class ShopTypeController { @Resource private IShopTypeService typeService; @GetMapping("/list") public Result queryTypeList() { // 只做一件事:调用service return Result.ok(typeService.queryTypeList()); } }
public interface IShopTypeService extends IService<ShopType> {
// 查询店铺类型列表(带缓存)
List<ShopType> queryTypeList();
}
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Resource
private StringRedisTemplate stringRedisTemplate;
private static final String KEY = "cache:shop:type:list";
@Override
public List<ShopType> queryTypeList() {
// 1. 查缓存
String json = stringRedisTemplate.opsForValue().get(KEY);
if (StrUtil.isNotBlank(json)) {
return JSONUtil.toList(json, ShopType.class);
}
// 2. 查数据库(标准写法!)
List<ShopType> list = query().orderByAsc("sort").list();
// 3. 写缓存
stringRedisTemplate.opsForValue().set(KEY, JSONUtil.toJsonStr(list));
return list;
}
}