表现层
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
@Resource
private IShopTypeService typeService;
@GetMapping("list")
public Result queryTypeList() {
/* List<ShopType> typeList = typeService.query().orderByAsc("sort").list();*/
return typeService.queryType();
}
}
业务层
public interface IShopTypeService extends IService<ShopType> {
Result queryType();
}
业务层实现
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Resource
private StringRedisTemplate stringRedisTemplate;
//由于是查固定列表,因此查询方法什么也不用传入
@Override
public Result queryType() {
//1先从redis中查看看缓存中有无
String shopTypeJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
//判断查到没有
if (StrUtil.isNotBlank(shopTypeJson)) {
//3存在,直接返回
List<ShopType> shopTypeList = JSONUtil.toList(shopTypeJson, ShopType.class);
return Result.ok(shopTypeList);
}
//4如redis没有,去查询数据库
List<ShopType> shopTypeList = this.query().orderByAsc("sort").list();
//5如果数据库也没有,返回错误信息
if (shopTypeList == null || shopTypeList.size() == 0) {
return Result.fail("商品类型查询失败");
}
//6数据库有,缓存进redis
stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopTypeList));
return Result.ok(shopTypeList);
}
}