Avalanche cache, the cache penetrate cache breakdown

What kind of data suitable for caching?

Whether a cache for data analysis, we need access frequency, the ratio of read and write, to analyze data consistency requirements.

  • The higher the frequency of data access
  • Read and write data ratio: less reading and writing,
  • Data consistency requires lower

Caching process flow

Reception request to take back existing cache data, to take a direct result of the return, whichever is less than when taken from the database, the database taken to update the cache, and returns the result, the database did not get to, that directly returns an empty result.

Cache avalanche

Description: cache invalidation same time a large area, so subsequent requests will fall on the database, resulting in a short time withstand a large number of database requests and bounced off.

Solution (China huperzine teacher said in his video over the video address mentioned in the last question):

  • Advance: try to ensure high availability of the entire cluster redis, machine downtime found to make up as soon as possible. Select the appropriate memory elimination strategy.

  • Things in: ehcache local cache + hystrix limiting & downgrade, MySQL avoid collapse out

  • Afterwards: use redis persistently saved data recovery cache mechanism as soon as possible

 

Cache penetration

Summary: General hackers intentionally requested data does not exist in the cache, initiating id such as '1' or data id is particularly large data does not exist, leading to all the requests fall to the database, resulting in a short time database withstand the large number of requests and collapse out,

Solution:

There are many ways to effectively solve the problem of penetration of the cache,

1. The most common is the use of a Bloom filter, the hash of all possible data to a bitmap large enough in the absence of a certain data out of this bitmap will be blocked, thus avoiding the underlying storage system queries pressure. There is also a more simple and crude way (we use is this), if a query returned an empty data (whether data does not exist, or system failure), we still see the empty cache results, but it's expiration time will be very short, no longer than five minutes.

2. Interface layer increases checkout, the user authentication check, id foundation check, id <= 0 direct interception;

3. reach of data from the cache, the database does not get to this time may be written as key-value pairs key-null, the cache valid time point can be set short as 30 seconds (set too long leads to normal circumstances would not be able to use). This prevents attacks repeatedly use the same user id violent attack

Cache breakdown

 描述:

     在高并发下,多线程同时查询同一个资源,如果缓存中没有这个资源,那么这些线程都会去数据库查找,对数据库造成极大压力,缓存失去存在的意义.打个比方,数据库是人,缓存是防弹衣,子弹是线程,本来防弹衣是防止子弹打到人身上的,但是当防弹衣里面没有防弹的物质时,子弹就会穿过它打到人身上. 

缓存击穿的解决办法

方案一

后台刷新

后台定义一个job(定时任务)专门主动更新缓存数据.比如,一个缓存中的数据过期时间是30分钟,那么job每隔29分钟定时刷新数据(将从数据库中查到的数据更新到缓存中).

这种方案比较容易理解,但会增加系统复杂度。比较适合那些 key 相对固定,cache 粒度较大的业务,key 比较分散的则不太适合,实现起来也比较复杂。

方案二

检查更新

将缓存key的过期时间(绝对时间)一起保存到缓存中(可以拼接,可以添加新字段,可以采用单独的key保存..不管用什么方式,只要两者建立好关联关系就行).在每次执行get操作后,都将get出来的缓存过期时间与当前系统时间做一个对比,如果缓存过期时间-当前系统时间<=1分钟(自定义的一个值),则主动更新缓存.这样就能保证缓存中的数据始终是最新的(和方案一一样,让数据不过期.)

这种方案在特殊情况下也会有问题。假设缓存过期时间是12:00,而 11:59
到 12:00这 1 分钟时间里恰好没有 get 请求过来,又恰好请求都在 11:30 分的时
候高并发过来,那就悲剧了。这种情况比较极端,但并不是没有可能。因为“高
并发”也可能是阶段性在某个时间点爆发。

方案三

分级缓存

采用 L1 (一级缓存)和 L2(二级缓存) 缓存方式,L1 缓存失效时间短,L2 缓存失效时间长。 请求优先从 L1 缓存获取数据,如果 L1缓存未命中则加锁,只有 1 个线程获取到锁,这个线程再从数据库中读取数据并将数据再更新到到 L1 缓存和 L2 缓存中,而其他线程依旧从 L2 缓存获取数据并返回。

这种方式,主要是通过避免缓存同时失效并结合锁机制实现。所以,当数据更
新时,只能淘汰 L1 缓存,不能同时将 L1 和 L2 中的缓存同时淘汰。L2 缓存中
可能会存在脏数据,需要业务能够容忍这种短时间的不一致。而且,这种方案
可能会造成额外的缓存空间浪费。

方案四

加锁

方法1

// 方法1:
public synchronized List<String> getData01() {
List<String> result = new ArrayList<String>();
// 从缓存读取数据
result = getDataFromCache();
if (result.isEmpty()) {
// 从数据库查询数据
result = getDataFromDB();
// 将查询到的数据写入缓存
setDataToCache(result);
}
return result;
}

 


这种方式确实能够防止缓存失效时高并发到数据库,但是缓存没有失效的时候,在从缓存中拿数据时需要排队取锁,这必然会大大的降低了系统的吞吐量.
方法2

// 方法2:
static Object lock = new Object();

public List<String> getData02() {
List<String> result = new ArrayList<String>();
// 从缓存读取数据
result = getDataFromCache();
if (result.isEmpty()) {
synchronized (lock) {
// 从数据库查询数据
result = getDataFromDB();
// 将查询到的数据写入缓存
setDataToCache(result);
}
}
return result;
}

 

这个方法在缓存命中的时候,系统的吞吐量不会受影响,但是当缓存失效时,请求还是会打到数据库,只不过不是高并发而是阻塞而已.但是,这样会造成用户体验不佳,并且还给数据库带来额外压力.


方法3

//方法3
public List<String> getData03() {
List<String> result = new ArrayList<String>();
// 从缓存读取数据
result = getDataFromCache();
if (result.isEmpty()) {
synchronized (lock) {
//双重判断,第二个以及之后的请求不必去找数据库,直接命中缓存
// 查询缓存
result = getDataFromCache();
if (result.isEmpty()) {
// 从数据库查询数据
result = getDataFromDB();
// 将查询到的数据写入缓存
setDataToCache(result);
}
}
}
return result;
}

 


双重判断虽然能够阻止高并发请求打到数据库,但是第二个以及之后的请求在命中缓存时,还是排队进行的.比如,当30个请求一起并发过来,在双重判断时,第一个请求去数据库查询并更新缓存数据,剩下的29个请求则是依次排队取缓存中取数据.请求排在后面的用户的体验会不爽.

方法4

static Lock reenLock = new ReentrantLock();

public List<String> getData04() throws InterruptedException {
List<String> result = new ArrayList<String>();
// 从缓存读取数据
result = getDataFromCache();
if (result.isEmpty()) {
if (reenLock.tryLock()) {
try {
System.out.println("我拿到锁了,从DB获取数据库后写入缓存");
// 从数据库查询数据
result = getDataFromDB();
// 将查询到的数据写入缓存
setDataToCache(result);
} finally {
reenLock.unlock();// 释放锁
}

} else {
result = getDataFromCache();// 先查一下缓存
if (result.isEmpty()) {
System.out.println("我没拿到锁,缓存也没数据,先小憩一下");
Thread.sleep(100);// 小憩一会儿
return getData04();// 重试
}
}
}
return result;
}

 

最后使用互斥锁的方式来实现,可以有效避免前面几种问题.
当然,在实际分布式场景中,我们还可以使用 redis、tair、zookeeper 等提供的分布式锁来实现.但是,如果我们的并发量如果只有几千的话,何必杀鸡焉用牛刀呢?

部分引用:https://blog.csdn.net/bushanyantanzhe/article/details/79459095

Guess you like

Origin www.cnblogs.com/ghl666/p/11936707.html