This is the fourth day of my participation in the More text Challenge. For details, see more text Challenge

Redis, because of its speed and other reasons, developers have been used in enterprise development.

Once you start using Redis, you must consider cache penetration and cache avalanche, which are easy points to ask during the interview process. Let’s talk about these.

1. What is cache penetration?

Cache penetration means that when querying a non-existent data, the corresponding value cannot be matched, and the database will always need to query. Therefore, at this time, Redis does not reduce the number of queries and lose the original intention of using Redis, but has greater consumption in terms of performance, which will cause the overall performance decline.

2. How do I solve the cache penetration problem?

One sentence answer: set 'null' for keys that missed.

We cannot match the corresponding value, but we still need to set the corresponding key to null value.

In this way, we can reduce the number of direct access to the database, thereby improving system performance to some extent.

3. What is a cache avalanche?

No snowflake is innocent in an avalanche.Copy the code

Cache avalanche means that when a batch of cached data is set to expire at the same time, a batch of cached data will become invalid at the same time. At that time, a large number of requests will be sent to access the database at the same time, resulting in excessive instantaneous pressure on the database, resulting in avalanche.

4. How do I solve the cache avalanche problem?

One sentence answer: set different expiration times for the keys that cache data

The cache avalanche problem is the same time cache expiration problem, so you just need to set different expiration times for the cache data.

Due to the limitations of internal services in the system, you can set a random value within a certain range, for example, any value between 30 minutes and 60 minutes. This way, even if there is the same expiration time, it will not be much.

Of course, if you have a large business cache, you can increase the range.