优点:降低负载 提高效率
缺点:数据一致性成本 代码维护成本 运维成本
将店铺信息存入redis的实现:
@Override
public Result queryById(Long id) {
// 1. 从Redis查询商铺缓存
String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
// 2. 判断是否存在
if(StrUtil.isNotBlank(shopJson)){
// 3. 如果存在,直接返回
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return Result.ok(shop);
}
// 4. 如果不存在,查询数据库
Shop shop = this.getById(id);
if(shop == null){
return Result.fail("商铺不存在");
}
// 5. 查询数据库后,将数据写入Redis
stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop));
return Result.ok(shop);
}