Redis cache failure story to start with the expire command, expire allows the user to specify a time-out for a key, and the value corresponding to the key will be erased after that time. This article mainly on the basis of the analysis of Redis source code to stand on the Redis designer's perspective to consider the problem of Redis cache failure. Redis cache invalidation mechanism
The Redis cache invalidation mechanism is designed to address a very common scenario for caching applications, speaking of a scenario:
In order to reduce the pressure on the back-end database, we are happy to use the Redis service to put the frequency of the change is not very high from the DB load into the cache, so for a period of time we can directly from the cache data, but we hope that after a period of time, we re-from the DB Load out the current data into the cache, what to do about it.
The question is raised, how to solve the problem. Well, we're very familiar with the language tools at hand, and we believe we can quickly write a logic like this: We record the last time we load data from DB, and then each time we respond to the service, we have to decide whether the time is out of date or to reload from the db .... Of course this method is also possible, but when we look at Redis command document, we find that we did what we didn't need to do, and Redis itself provides this mechanism, and we can do it easily with the help of the expire command:
Shell
The above command is the key set 30 seconds to expire, more than this time, we should not access this value, so far we probably understand what is the cache invalidation mechanism and caching failure mechanism of some scenarios, then we continue to delve into this problem, How is the Redis cache invalidation mechanism implemented? delay failure Mechanism
The delay failure mechanism is that when a client requests a key, Redis checks the key for the client request operation, and if the key expires to handle it, the delay mechanism is also called the negative failure mechanism. Let's look at the service end-side execution stack facing GET request processing under the T_string component:
Shell
1 2 3) 4 5 |
Lookupkeyread, Lookupkeyreadorreply, GetCommand, Getgenericcommand, expireifneeded |
The key point is that the Expireifneed,redis Key's get operation will determine if the value associated with the key is invalidated, insert an episode first, and let's look at where the value is actually stored in Redis:
Shell