修改ShopController中的业务逻辑,满足以下两个需求:
1、根据id查询店铺时,如果缓存未命中,则查询数据库,将数据库结果写入缓存,并设置超时时间
java
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryById(Long id) {
//1.从redis查商铺缓存
String key =CACHE_SHOP_KEY + id;
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在 如果不为空(存在)
if(StrUtil.isNotBlank(shopJson)){
//3.存在,直接返回
//反序列化json
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return Result.ok(shop);
}
//4.不存在,根据id查数据库
Shop shop = getById(id);
//5.数据库不存在,返回错误
if(shop == null){
return Result.fail("店铺不存在");
}
//6.存在,写入redis
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
//7.返回
return Result.ok(shop);
}
}
2、根据id修改店铺时,先修改数据库,再删除缓存
java
@PutMapping
public Result updateShop(@RequestBody Shop shop) {
// 写入数据库
// shopService.updateById(shop);
return shopService.update(shop);
}
java
@Override
@Transactional
public Result update(Shop shop) {
Long id = shop.getId();
if(id == null){
return Result.fail("店铺id不能为空");
}
//写入数据库
updateById(shop);
//删除缓存
stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
return Result.ok();
}