当前位置:网站首页>I haven't encountered these three problems. I'm sorry to say that I used redis
I haven't encountered these three problems. I'm sorry to say that I used redis
2022-06-29 04:40:00 【Liushuijing】
Caching is an indispensable part of Internet applications . When it comes to caching , I have to ask three classic questions —— Cache penetration 、 Cache breakdown and cache avalanche , I call them the three brothers of cache problems .
Cache has two main functions : To improve access speed ; Second, to protect the database . When the business is small , Usually there is no big problem . But when the business volume increases , If the cache is not properly used , The three brothers will come as promised , Let you experience the cruelty of reality .
If the three brothers don't come, they will be gone , One light will affect the system performance , The most important thing is to directly drag down the database , Cause system paralysis . therefore , We should not take it lightly , Be prepared for the unexpected .
Cache penetration
When a request arrives at the server , Under normal circumstances, the following process is followed .

Follow the steps below :
- The query cache , Return... If hit
- Cache miss , Then query the database
- Write the data queried from the database into the cache and return
If you do this step by step every time , It's all right . however , I'm afraid of everything, but . But there are always exceptions , If the requestor is interested in a ( In the database ) Access to data that does not exist at all , So follow the above process , The cache is useless . Because it doesn't exist , So it will not be written to the cache , In this way, every request will be sent to the database , This phenomenon is called 「 Cache penetration 」 了 .
If you only query nonexistent data because of individual requests , That's no big deal . But cache penetration is usually accompanied by some 「 Malicious request 」 And come , It is usually an influx of requests in a short time . If you let it go , Just wait for the database to go down .
How to solve
Understand the causes of cache penetration , Then the solution is clear . We can start from two aspects :
- Cache nonexistent records
- Filter non-existent requests
what ? How to cache nonexistent records ? It's very simple , If you can't find it in the database , Then cache the value Set to null that will do ( Pay attention to setting reasonable expiration time according to business characteristics ).
Filter non-existent requests , When a request arrives at the server , such as :
GET /api/user/1
The filter will first determine whether the resource exists , Release if present , Return directly if it does not exist , So as to protect the system .
There are also mature schemes for this method . Such as Bloom filter and cuckoo filter ( Upgraded bronbronbron filter ).
Double reinforcement
Whether the request for a nonexistent resource is intentional or unintentional , It's not what we want . therefore , We can set an access frequency , Frequently within a certain period of time ( Beyond the limit of normal users ) visit , The requesting party may be restricted ( Such as IP Limit ). in addition , Some interfaces can be authenticated , You have to log in to access .
Cache breakdown
General situation , We will set an expiration time for the cache . If the cache of a resource expires ( Or you haven't had time to cache ), An instant influx of requests to query this resource , Then these requests will rush to the database , At this time , Our database is miserable , Maybe I will die every second . This situation is called cache breakdown .
How to solve
There are two ways to solve cache breakdown :
- Never expire
- Lock
First look at the first one , Hot resources are often accessed in large numbers in a short time , For such resources, we can not set the expiration time ( Never expire ), Update the cache through the program when the resources change .
Let's look at the second one , We can use a lock ( commonly JVM Level lock ) To avoid breakdown . When the cache expires , The request to come in , First get a lock ( That is, the qualification to query the database ), Then go to query the database , Finally, add the data to the cache . This will ensure the same time ( A service instance ) There will only be one request to check the database , Other threads wait until the cache has a value , Then go to cache to fetch .
Lock pseudo code example :
public String getData() throws InterruptedException {
// Fetch from cache
String result = getFromCache();
// Take it and return to
if (Objects.nonNull(result)) {
return result;
}
// Attempt to acquire lock
if (!lock.tryLock()) {
// If locking fails, take a break
Thread.sleep(10);
return getData();
}
// If the lock is successful, go to the database to get the value
result = getFromDB();
// Retrieve and put it into the cache
setFromCache();
return result;
}
Cache avalanche
Cache avalanche means , A lot of... In the cache key Collective expiration at the same time , Result in a large number of requests pouring into the database .
Some people call cache service unavailable for some reasons as cache avalanche , I don't think it's appropriate to call it that .
Imagine what an avalanche is , A large number of snowflakes jumping down from the mountain is an avalanche . Then the scene corresponding to the cache , We can Redis As a mountain , and Redis Inside key It's snowflakes .Redis In large quantities key Simultaneous failure , It's like a lot of snowflakes falling down on the mountain at the same time . So avalanches are used to describe a large number of key Centralized failure is obviously more appropriate . The cache service failure should be attributed to the cache service failure , You can use a cache cluster to improve availability .
How to solve
To solve the problem of cache avalanche , There are two ways of thinking :
- Scatter expiration time
- Never expire
Scattered expiration times are easy to think of , Since the avalanche is caused by key Collective expiration , Then the problem can be avoided by dispersing their expiration time .
Another way to think about it , It is the same as solving cache breakdown , Set the cache to never expire .
The never - expired scheme has certain limitations , It depends on the specific business , You can't brutally set all caches to not expire .
summary
Each technical solution has its applicable business scenario , They all have their limitations . No one solution can deal with all the problems , Appropriate is good . But we can still see some general ideas from the above scheme , such as : Return as soon as possible . How to understand ? Is to make the call chain as short as possible , Never release those that can be stopped before the application service ( Bloon filtration ); Never look up the database if you can get it from the cache .
More exclusive highlights are in my new book 《Spring Boot Interesting practical class 》 in .
边栏推荐
- Canoe- how to parse messages and display information in the trace window (use of program node and structure type system variables)
- Gbase 8s must be a DBSA. Solution to failure to start due to path change
- LabVIEW displays Unicode characters
- Command pattern
- 软件体系结构实验汇总
- PostgreSQL has a cross database references are not implemented bug
- Redis 缓存穿透、缓存击穿、缓存雪崩
- JDBC learning
- Complete collection of necessary documents for project management: you can't write these 14 project documents yet?
- Mécanisme d'attention du canal de fixation
猜你喜欢

Untitled

Live broadcast appointment AWS data everywhere series activities
![[结构力学] 结点承载下影响线与直接承载下影响线不同的原因](/img/a6/fce0bb29cc5c84bc0ef20501617e06.png)
[结构力学] 结点承载下影响线与直接承载下影响线不同的原因

Network device setting / canceling console port login separate password

EEG signal processing - wavelet transform series

泰克DPO4104数字荧光示波器技术参数

How to quickly change the database name in MySQL

It is said on the Internet that a student from Guangdong has been admitted to Peking University for three times and earned a total of 2million yuan in three years

安捷伦数字万用表软件NS-Multimeter,实时数据采集数据自动保存

Redis 缓存穿透、缓存击穿、缓存雪崩
随机推荐
What are the MySQL database constraint types
Developer scheme · environmental monitoring equipment (Xiaoxiong school IOT development board) connected to graffiti IOT development platform
Research Report on the overall scale, major manufacturers, major regions, product and application segmentation of the gsm-gprs-edge module of the Internet of things in the global market in 2022
网络设备设置/取消console口登陆单独密码
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of GPS antenna modules in the global market in 2022
Research Report on the overall scale, major manufacturers, major regions, products and application segments of semiconductor wafer metal stripping platform in the global market in 2022
GBASE 8s must be a DBSA、路径更改导致无法启动的解决方法
LabVIEW displays Unicode characters
What is the method of connection query in MySQL
Decorator Pattern
Quelles sont les méthodes de simulation et de gravure des programmes? (comprend les outils communs et la façon dont ils sont utilisés)
Network device setting / canceling console port login separate password
044. (2.13) add value to yourself
How to quickly install MySQL 5.7.17 under CentOS 6.5
Gocd is good, but talk about Jenkins
JVM内存调优方式
Open source demo| you draw and I guess -- make your life more interesting
剑指 Offer II 040. 矩阵中最大的矩形
Cisco voice card handling configuration
Command pattern