1 缓存穿透
缓存穿透是指缓存和数据库中都没有的数据,而用户不断发起请求,如发起为id为“-1”的数据或id为特别大不存在的数据。这时的用户很可能是攻击者,攻击会导致数据库压力过大。如下面这段代码就存在缓存穿透的问题。
public Integer findPrice(Long id) {
//从缓存中查询
Integer sku_price =(Integer)redisTemplate.boundHashOps("sku_price").get(id);
if(sku_price==null){
//缓存中没有,从数据库查询
Sku sku = skuMapper.selectByPrimaryKey(id);
if(sku!=null){ //如果数据库有此对象
sku_price = sku.getPrice();
redisTemplate.boundHashOps("sku_price").put(id,sku_price);
}
}
return sku_price;
}
解决方案:
- 接口层增加校验,如用户鉴权校验,id做基础校验,id<=0的直接拦截;
- 从缓存取不到的数据,在数据库中也没有取到,这时也可以将key-value对写为
key-0。这样可以防止攻击用户反复用同一个id暴力攻击。代码举例:
public int findPrice(Long id) {
//从缓存中查询
Integer sku_price =(Integer)redisTemplate.boundHashOps("sku_price").get(id);
if(sku_price==null){
//缓存中没有,从数据库查询
Sku sku = skuMapper.selectByPrimaryKey(id);
if(sku!=null){ //如果数据库有此对象
sku_price = sku.getPrice();
redisTemplate.boundHashOps("sku_price").put(id,sku_price);
}else{
redisTemplate.boundHashOps("sku_price").put(id,0);
}
}
return sku_price;
}
- 使用缓存预热:
缓存预热就是将数据提前加入到缓存中,当数据发生变更,再将最新的数据更新到缓存。
2 缓存击穿
缓存击穿是指缓存中没有但数据库中有的数据。这时由于并发用户特别多,同时读缓存没读到数据,又同时去数据库去取数据,引起数据库压力瞬间增大,造成过大压力。
以下代码可能会发生缓存击穿:
@Autowired
private RedisTemplate redisTemplate;
public List<Map> findCategoryTree() {
//从缓存中查询
List<Map> categoryTree=(List<Map>)redisTemplate.boundValueOps("categoryTree").get();
if(categoryTree==null){
Example example=new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo("isShow","1");//显示
List<Category> categories =
categoryMapper.selectByExample(example);
categoryTree=findByParentId(categories,0);
redisTemplate.boundValueOps("categoryTree").set(categoryTree);
//过期时间设置 ......
} return categoryTree;
}
解决方案:
- 设置热点数据永远不过期。
- 使用缓存预热
3 缓存雪崩
缓存雪崩是指缓存数据大批量到过期时间,而查询数据量巨大,引起数据库压力过大甚至down机。和缓存击穿不同的是,缓存击穿指并发查同一条数据,缓存雪崩是不同数据都过期了,很多数据都查不到从而查数据库。
解决方案:
- 缓存数据的过期时间设置随机,防止同一时间大量数据过期现象发生。
- 设置热点数据永不过期
- 使用缓存预热
缓存预热就是将数据提前加入到缓存中,当数据发生变更,再将最新的数据更新到缓存。