【黑马点评缓存练习】
实现商铺查询缓存:
ShopTypeController类:
@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 Result.ok(typeList);
return typeService.queryList();
}
}
IShopTypeService接口:
public interface IShopTypeService extends IService<ShopType> {
Result queryList();
}
ShopTypeServiceImpl类:
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryList() {
// 1.在redis中查询店铺类型缓存
String key = SHOP_TYPE_KEY + "list";
List<String> stringTypeList = stringRedisTemplate.opsForList().range(key, 0, -1);
// 2.判断是否命中
if (!stringTypeList.isEmpty()) {
// 3.命中,直接返回
// List<String> ===> List<?>
List<ShopType> shopTypeList = JSONUtil.toList(stringTypeList.toString(), ShopType.class);
return Result.ok(shopTypeList);
}
// 4.没有命中,查询数据库
List<ShopType> typeList = query().orderByAsc("sort").list();
// 5.判断数据库中是否存在
if (typeList == null) {
// 6.不存在,返回错误信息
return Result.fail("店铺类型不存在!");
}
// 7.存在,存入redis
// List<?> ===> List<String>
stringTypeList = JSONUtil.toList(new JSONArray(typeList), String.class);
stringRedisTemplate.opsForList().rightPushAll(key, stringTypeList);
// 8.返回
return Result.ok(typeList);
}
}
