Key expiration feature
Let Redis automatically delete specific keys at a specified time. key expiration feature related commands
type |
Command |
Set the time to live |
EXPIRE command and Pexpire command. |
Set Expiration Time |
expireat command and Pexpireat command. |
View remaining live time |
The TTL command and the Pttl command. |
Delete Time to live or expire |
PERSIST command. |
EXPIRE Key seconds
Sets the time-to-live of key keys to the specified number of seconds.
Pexpire key milliseconds
Sets the time-to-live of key key to the specified number of milliseconds.
If the given key does not exist, then EXPIRE and Pexpire will return 0, indicating that the setting failed, and that if the command returns 1, the setting is successful.
Expireat key Timestamp
Set the expiration time for key key to the specified second-level UNIX timestamp.
Pexpireat Key Milliseconds-timestamp
Sets the expiration time for key key to the specified millisecond-level UNIX timestamp.
If the given key does not exist, then expireat and Pexpireat will return 0, indicating that the setting failed, and that if the command returns 1, the setting is successful.
TTL Key
Returns the remaining lifetime of the key, in seconds.
Pttl Key
Returns the remaining life time of the key, in milliseconds.
TTL and Pttl may return three different values:
return value |
meaning |
-2 |
The key does not exist. |
-1 |
The key exists but does not set the expiration time or the time to live. |
= 0 |
The remaining life time of the key. |
PERSIST Key
Removes the expiration time or the lifetime of the key set, making it not automatically deleted by Redis. application of key expiration function
Automatically updates the cache, automatically refreshes the leaderboard, and periodically deletes the user Session.
Setex Key seconds value
The value of the SET key key is value,seconds seconds after expiration
Psetex Key milliseconds value
The value of the SET key key is value,milliseconds milliseconds after expiration
Although both Setex and Psetex are working normally, I recommend using set instead of Setex or Psetex as much as possible, because using set to set the time to live is more concise, whereas older Setex and Psetex may be discarded in the future.