定义
缓存穿透
当查询的数据缓存和数据库中都不存在时,此时查询无法命中缓存,因此每次请求都会打到数据库,大量这样的查询导致数据库压力增大甚至崩溃。
解决方法
基础校验
要求ID符合某种格式,不符合格式的直接拦截。
缓存空值
public UserDTO getUser(int id){
String key = "user:" + id;
String userJson = stringRedisTemplate.opsForValue().get(key);
// 空值直接返回
if(userJson == ""){
throw new RuntimeException();
}
if(userJson != null){
User user = toUser(userJson);
return toUserDTO(user);
}
User user = getById(id);
if(user == null){
// 不存在时缓存空值
stringRedisTemplate.opsForValue().set(key, "");
throw new RuntimeException();
}
stringRedisTemplate.opsForValue().set(key, toJson(user));
return toUserDTO(user);
}