当前位置:网站首页>Three must know and know problems of redis
Three must know and know problems of redis
2022-07-25 04:59:00 【nginx】

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 .
I haven't encountered these three problems. I'm sorry to say I used them Redis
Follow the steps below :
1. The query cache , Return... If hit .
2. Cache miss , Then query the database .
3. 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 :
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 .
GET /api/user/1
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 :
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 .
public String getData() throws InterruptedException {// Fetch from cacheString result = getFromCache();// Take it and return toif (Objects.nonNull(result)) {return result;}// Attempt to acquire lockif (!lock.tryLock()) {// If locking fails, take a breakThread.sleep(10);return getData();}// If the lock is successful, go to the database to get the valueresult = getFromDB();// Retrieve and put it into the cachesetFromCache();return result;}
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 .
边栏推荐
- 深入掌握Pod
- 数据链路层协议 ——— 以太网协议
- Redis的三个必知必会的问题
- 绕过 Web 应用程序中的 XSS 过滤器
- Data link layer protocol -- Ethernet protocol
- China trifluoroethanol industry research and investment forecast report (2022 Edition)
- 盐粒和冰粒分不清
- Unity LOD
- Ownership in rust -- introduction of rust language Xiaobai 11
- Information System Project Manager --- Chapter IX examination questions of project human resource management over the years
猜你喜欢
![[wechat applet] design and interactive implementation of auction product details page (including countdown and real-time update of bids)](/img/01/42de6280191b9c32a7f37d7727bd4f.png)
[wechat applet] design and interactive implementation of auction product details page (including countdown and real-time update of bids)

Teach you how to locate unreasonable SQL? And optimize it

How to ensure data consistency between MySQL and redis?

Why does the official not recommend using UUID as MySQL primary key

The interviewer asked MySQL transactions, locks and mvcc at one go. I

85 distributed project construction
![[analysis of GPIO register (crl/crh) configuration of STM32]](/img/63/a7b262e95f1dc74201ace9d411b46f.png)
[analysis of GPIO register (crl/crh) configuration of STM32]

Unity 之 UPR优化建议汇总
![[untitled]](/img/6c/df2ebb3e39d1e47b8dd74cfdddbb06.gif)
[untitled]

After watching the latest interview with big manufacturers, these six JVM interview questions were asked
随机推荐
数据链路层协议 ——— 以太网协议
Data Lake (16): structured streaming writes iceberg in real time
Thinking from the perspective of Aya
很多时候都是概率
市场是对的
Getting started with scratch
IT自媒体高调炫富,被黑客组织盯上,铁定要吃牢饭了…
[untitled]
教你如何定位不合理的SQL?并优化之
Libenent and libev
The interviewer asked MySQL transactions, locks and mvcc at one go. I
Dark king | analysis of zego low illumination image enhancement technology
QT download installation tutorial
小红书携手HMS Core,畅玩高清视界,种草美好生活
Burpsuite爆破之token值替换
实战|记一次攻防演练打点
956. Highest billboard pressure DP
【浅析STM32之GPIO寄存器(CRL/CRH)配置 】
How can I check if the number of RDS links in MySQL suddenly rises?
STM32 development note 120: solve the problem that%f in printf cannot be output