1、缓存穿透问题
前端发起查询请求,查询数据库为空,不会存入redis缓存。下次发起同样的查询请求,由于缓存未命中,仍然会查询底层数据库,缓存一直未起到应有的作用,当并发流量大时,可能会导致后端压力过大甚至宕机。这就是缓存穿透问题。
/**
* 缓存穿透问题
* 查询数据库没有查询到数据,未存入缓存
* 下次查询同样的数据是,仍然查询数据库
*/
private ObjectgetObjectById(Integer id){
//从缓存查询数据
Object cacheValue = cache.get(id);
if (cacheValue !=null)
return cacheValue;
//从数据库查询数据
Object storageValue = storage.get(id);
if (storageValue !=null)
cache.set(id,storageValue);
return storageValue;
}
2、缓存穿透问题解决方案一
/**
* 缓存空对象
* 直接将Null对象存入缓存,并设置过期时间。防止恶意攻击。
*
*/
private ObjectgetObjectById(Integer id){
//从缓存查询数据
Object cacheValue = cache.get(id);
if (cacheValue ==null){
//从数据库查询数据
Object storageValue = storage.get(id);
cache.set(id,storageValue);
if (storageValue ==null)
cache.expire(id,60*10);
return storageValue;
}
return cacheValue;
}