缓存穿透例子:
@Autowired
private RedisTemplate redisTemplate;
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;
}
解决缓存穿透:
1.接口层增加校验,如用户鉴权校验,id做基础校验,id<=0的直接拦截;
2.从缓存取不到的数据,在数据库中也没有取到,这时也可以将key-value对写为 key-0。这样可以防止攻击用户反复用同一个id暴力攻击。
3. 使用缓存预热(缓存预热就是将数据提前加入到缓存中,当数据发生变更,再将最新的数据更新到缓存,常用于电商系统的分类导航、广告轮播等),缓存预热——数据的读取直接在缓存中执行,如果读取不到数据也不再向数据库中请求获取数据,避免了数据库访问压力增大。
结合1、2点代码举例:
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;
}
缓存击穿是指缓存中没有数据但数据库中有数据。这时由于缓存时间期限内并发用户特别多,同时读缓存没读到数据,又同时去数据库去取数据,引起数据库压力瞬间增大,造成过大压力。
图解:
缓存击穿例子:
@Autowired
private RedisTemplate redisTemplate;
public List
//从缓存中查询
List
(List
if(categoryTree==null){
Example example=new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo(“isShow”,“1”);//显示
List categories =categoryMapper.selectByExample(example);
categoryTree=findByParentId(categories,0);
redisTemplate.boundValueOps(“categoryTree”).set(categoryTree);
//过期时间设置 (过期时间一过,就要进行重新请求,容易导致缓存击穿)…
//SECONDS 秒
redisTemplate.boundValueOps("categoryTree ").expire(30, TimeUnit.SECONDS);
}
return categoryTree;
}
解决缓存击穿:
1.设置热点数据永远不过期(过期时间设置)。
2.缓存预热。
3.添加互斥锁,解决并发用户,
以3为例:
public List
//从缓存中查询
List
if(categoryTree==null){//缓存没数据
//获取锁成功,去数据库取数据
if (reenLock.tryLock()){
Example example=new Example(Category.class);
Example.Criteria criteria = example.createCriteria();
criteria.andEqualTo(“isShow”,“1”);//显示
List categories =categoryMapper.selectByExample(example);
categoryTree=findByParentId(categories,0);