Redis (5): about expired keys (1) setting, getting and deleting expired keys
Set expiration
By default, keys have no lifetime, that is, they never expire unless the memory is cleared.
The lifetime of the set key is also easy, and can be set by four commands (either): EXPIRE, PEXPIRE, EXPIREAT, and PEXPIREAT commands, which look different but are all implemented in the same way. The commonly used ones are EXPIRE and PEXPIRE, the former setting the expiration time in seconds and the latter in milliseconds.
Set in seconds, set the aaa key to expire after 1 second, and get the aaa key later in 1 second will return null.
Set in milliseconds. Set the bbb key to expire after 10 milliseconds.
The command states that EXPIREkey # s sets the lifetime of KEY to # seconds PEXPIREkey # ms sets the lifetime of KEY to # milliseconds EXPIREATkey timestamp sets the lifetime of KEY to UNIX timestamp, in seconds
PEXPIREATkey timestamp sets the lifetime of KEY to the UNIX timestamp, in milliseconds
The above four commands are only different in units and representations, but in fact, the execution of EXPIRE, PEXPIRE, and EXPIREAT commands will end up using PEXPIREAT.
For example, if you use EXPIRE to set the lifetime of KEY to N seconds, how does the background run:
It calls the PEXPIRE command to convert N seconds to M milliseconds.
Then get the current UNIX time unit in milliseconds
Pass the current UNIX time plus M milliseconds to PEXPREAT
Set the expiration time for the key, which is saved in a dictionary, which is also the key value structure, the key is a pointer to the real key, and the value is a long integer UNIX time.
Get the expiration time of the key
How to find out how long a key can live? You can use ttl key to get it (shown in seconds), as shown below:
Another command is pttl key, which is displayed in milliseconds.
Expiration time of the clear key
You can use the PERSIST command to remove the expiration time of a key, as shown below:
Description of the return value of the expiration time
You can get the integer return value of a key through ttl
The value indicates that-2 expires and has been deleted-1 has no expiration time setting, that is, never expire > 0 indicates how many seconds or milliseconds are left before expiration