Expiration time of keys
Typically, the Redis keys are created without setting the associated expiration time. They will always exist unless you use the displayed command to remove them, for example, by using the Del command.
Expire a class of commands can be associated with a key with an extra memory overhead. When the key performs an expiration operation, Redis ensures that they are deleted at the specified time.
The Expiration time and permanent validity of a key can be updated by expire and persist commands (or other related commands) or by deleting an expiration date. Expiration Precision
In Redis 2.4 and previous versions, the expiration time may not be very accurate, with 0-1 seconds of error.
From Redis 2.6, the expiration time error is reduced to 0-1 milliseconds. Expired and persistent
The keys expire in milliseconds using the UNIX timestamp store (starting with Redis 2.6). This means that even if the Redis instance is not available, time has been passing by.
The computer must adopt a stable time to handle the overdue work well. If you sync RDB files between computers that are not synchronized between the two clocks, interesting things will happen (all keys will expire when loaded).
Even if the running instance checks the computer's clock, for example if you set a key that is valid for 1000 seconds and then sets your computer time for the next 2000 seconds, the key will immediately expire instead of waiting 1000 seconds. Redis How to retire the expired keys
The Redis keys expire in two ways: passive and active .
When some clients try to access it, the key is found and actively expires.
Of course, this is not enough, because some of the expired keys will never visit them. In any case, these keys should expire, so timed random tests set the keys ' Expiration time. All of these expired keys will be removed from the key space.
The exact thing is Redis 10 times per second:
Test a random 20 keys for related expiration detection.
Deletes all keys that have expired.
If more than 25% keys expire, repeat step 1.
This is a trivial probability algorithm , basically the assumption is that our sample is the key control, and we continue to repeat the expiration of detection, until the expired keys hundred percent less than 25%, which means that at any given time, the maximum will be cleared 1/4 of the expired keys. How to handle expiration when copying a aof file
In order to get the right behavior without sacrificing consistency, when a key expires, Del will be combined with aof text to all the additional slaves. In the master instance, this method is centralized, and there is no chance of a consistency error.
However, when slaves connects to master, it will not be independent of the expired keys (which will wait until master executes the del command), and they will still exist in the dataset, so when Slave is selected as master, the elimination keys execute independently and become master.