Redis缓存处理问题

在这里插入图片描述

缓存穿透例子:

@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 findCategoryTree() {

//从缓存中查询

List categoryTree=

(List)redisTemplate.boundValueOps(“categoryTree”).get();

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 findCategoryTree() {

//从缓存中查询

List categoryTree=(List)redisTemplate.boundValueOps(“categoryTree”).get();

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值