1.缓存查询
在service层Impl文件中,进行查询时优先向Redis中查数据,查到就查到了,没有查到向mysql数据库中查,查到之后不先返回,而是先将数据存到数据库(缓存),在再返回数据。
1.1 代码实现(缓存使用字符串)
controller层正常调用service层中的接口,在Impl中
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryById(Long id) {
String key = CACHE_SHOP_KEY + id;
String shopJson = stringRedisTemplate.opsForValue().get(key);
if (StrUtil.isNotBlank(shopJson)){
Shop shop = JSONUtil.toBean(shopJson, Shop.class);//将JSON转成制定类型对象
return Result.ok(shop);
}
Shop shop = getById(id);
if (shop == null){
return Result.fail("不存在");
}
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop));//将对象转成json
return Result.ok(shop);
}
}
2.缓存更新
在缓存的时候添加有效期
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
@Override
@Transactional
public Result update(Shop shop) {
Long id = shop.getId();
if (id == null){
return Result.fail("Id不可以为空");
}
//1.更新数据库
updateById(shop);
//2.删除缓存
stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
return Result.ok();
}
3.缓存穿透
缓存穿透 :缓存穿透是指客户端请求的数据在缓存中和数据库中都不存在,这样缓存永远不会生效,这些请求都会打到数据库。
常见的解决方案有两种:
- 缓存空对象
- 优点:实现简单,维护方便
- 缺点:
- 额外的内存消耗
- 可能造成短期的不一致
- 布隆过滤
- 优点:内存占用较少,没有多余key
- 缺点:
- 实现复杂
- 存在误判可能
编码解决商品查询的缓存穿透问题:
@Override
public Result queryById(Long id) {
String key = CACHE_SHOP_KEY + id;
//1.从redis查询缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
//2.判断是否存在 blank(空白字符(空格字符,制表符,换行符))
if (StrUtil.isNotBlank(shopJson)){
//3.存在直接返回
Shop shop = JSONUtil.toBean(shopJson, Shop.class);
return Result.ok(shop);
}
//4.判断是否为空
if (shopJson != null){
return Result.fail("不存在");
}
//5.向数据库查询
Shop shop = getById(id);
if (shop == null){
//数据库不存在,向redis存入null值,存活时间弄短一些
stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
return Result.fail("不存在");
}
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
return Result.ok(shop);
}
缓存雪崩问题及解决思路
缓存雪崩是指在同一时段大量的缓存key同时失效或者Redis服务宕机,导致大量请求到达数据库,带来巨大压力。
解决方案:
- 给不同的Key的TTL添加随机值
- 利用Redis集群提高服务的可用性
- 给缓存业务添加降级限流策略
- 给业务添加多级缓存