A Redis key can have an optional timeout, which makes the key expire after a certain amount of time, or at a certain time. We can use a couple of methods to remove any timeout associated with a key.
Here are two ways to remove a key’s expiry in Redis.
Option 1: The PERSIST
Command
The PERSIST
command was designed specifically for removing any timeout associated with a key. Suppose we set the following key with an expiry:
SET color "Blue" EX 3600
Result:
OK
We can check its current time to live like this:
TTL color
Result:
(integer) 3594
We can use the PERSIST
command to remove its timeout like this:
PERSIST color
Result:
(integer) 1
An integer reply of 1
indicates that the expiry was removed.
Now let’s check the current time to live again:
TTL color
Result:
(integer) -1
This result tells us that the key exists, but it has no associated expiry. The key’s expiry has been successfully removed.
Option 2: The GETEX
Command
When using strings, another way to do it is with the GETEX
command. This is a string command that allows us to return the key’s value and optionally set an expiry or remove an existing expiry. Therefore, we can use this command if we want to return the key’s value and remove its expiry in one go.
Let’s set the key’s expiry again:
EXPIRE color 3600
Result:
(integer) 1
This time we used the EXPIRE
command to set the timeout of the existing key. The integer reply of 1
means that the expiry was set successfully.
Now let’s check its current TTL:
TTL color
Result:
(integer) 3566
Now let’s use the GETEX
command to get the key’s value and remove its timeout.
To remove the existing expiry, we need to use the PERSIST
option:
GETEX color PERSIST
Result:
"Blue"
Now let’s check the TTL:
TTL color
Result:
(integer) -1
This result shows that the key now has no associated expiry.