Redis cache penetration, cache breakdown, cache avalanche difference and solutions

1. Cache processing flow

  前台请求,后台先从缓存中取数据,取到直接返回结果,取不到时从数据库中取,数据库取到更新缓存,并返回结果,数据库也没取到,那直接返回空结果。

Insert picture description here

2. Cache penetration

  描述:

   缓存穿透是指缓存和数据库中都没有的数据,而用户不断发起请求,如发起为id为“-1”的数据或id为特别大不存在的数据。这时的用户很可能是攻击者,攻击会导致数据库压力过大。

  解决方案:

The interface layer adds verification, such as user authentication verification, id for basic verification, and direct interception for id<=0;
data that cannot be retrieved from the cache is also not retrieved in the database. At this time, you can also set the key- The value pair is written as key-null, and the cache valid time can be set to a short point, such as 30 seconds (setting too long will cause it to be unusable under normal conditions). This can prevent attacking users from repeatedly using the same id brute force attack

Three, cache breakdown

  描述:

  缓存击穿是指缓存中没有但数据库中有的数据(一般是缓存时间到期),这时由于并发用户特别多,同时读缓存没读到数据,又同时去数据库去取数据,引起数据库压力瞬间增大,造成过大压力

  解决方案:

Set hotspot data to never expire.
Add the mutex lock, the reference code for the mutex lock is as follows:
Insert picture description here

      说明:

      1)缓存中有数据,直接走上述代码13行后就返回结果了

     2)缓存中没有数据,第1个进入的线程,获取锁并从数据库去取数据,没释放锁之前,其他并行进入的线程会等待100ms,再重新去缓存取数据。这样就防止都去数据库重复取数据,重复往缓存中更新数据情况出现。

      3)当然这是简化处理,理论上如果能根据key值加锁就更好了,就是线程A从数据库取key1的数据并不妨碍线程B取key2的数据,上面代码明显做不到这点。

Fourth, the cache avalanche

  描述:

  缓存雪崩是指缓存中数据大批量到过期时间,而查询数据量巨大,引起数据库压力过大甚至down机。和缓存击穿不同的是,        缓存击穿指并发查同一条数据,缓存雪崩是不同数据都过期了,很多数据都查不到从而查数据库。

 解决方案:

1: The expiration time of cached data is set randomly to prevent a large amount of data from expiring at the same time.
2: If the cache database is a distributed deployment, evenly distribute the hot data in different cache databases.
3: Set hotspot data to never expire.

Guess you like

Origin blog.csdn.net/weixin_55580097/article/details/114171823