根据id查询商品:
添加redis缓存(增强读写功能)步骤
1.从redis中获取商品信息,判断信息是否存在
2.若存在则从redis中获取,不存在则直接查询数据库
3.若数据库中不存在则返回错误信息
4.若数据库中存在则同同样将信息存入redis中
controller层
@GetMapping("/{id}")
public Result queryShopById(@PathVariable("id") Long id) {
return shopService.queryById(id);
}
service层
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryById(Long id) {
String key=CACHE_SHOP_KEY+id;
//从redis查询商品缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
//判断是否命中,若命中
if(StrUtil.isNotBlank(shopJson)){
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return Result.ok(shop);