The Redis GETEX
command enables us to get the value of a key, then set the key’s expiration. We can also use it to remove any existing expiration associated with the key.
Syntax
GETEX key [ EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | PERSIST]
The following table explains what each argument means:
EX seconds | Sets the specified expire time, in seconds. |
PX milliseconds | Sets the specified expire time, in milliseconds. |
EXAT timestamp-seconds | Sets the specified Unix time at which the key will expire, in seconds. |
PXAT timestamp-milliseconds | Sets the specified Unix time at which the key will expire, in milliseconds. |
PERSIST | Removes the time to live (TTL) associated with the key. |
Example
Suppose we set a key like this:
SET composer "Beethoven"
Result:
OK
And now let’s check its TTL:
TTL composer
Result:
(integer) -1
A result of -1
means that there is no TTL associated with the key. It has no expiry.
Now let’s use GETEX
to get its value and set a TTL:
GETEX composer EX 30
Result:
"Beethoven"
That shows us the key’s value, and behind the scenes it set an expiry.
Now, if we run the TTL command again before the 30 seconds is up, we can see its TTL:
TTL composer
Result:
(integer) 18
That tells us that it’s already down to 18. The key will expire in 18 seconds.
And if I’m quick, I can try again before it expires:
TTL composer
Result:
(integer) 9
Now it’s down to 9.
Let’s wait until the full 30 seconds has passed and run TTL again:
TTL composer
Result:
(integer) -2
This time we get -2
, which means that the key doesn’t exist. It has expired.
As shown in the table above, we can use other methods to set the TTL, such as milliseconds or a Unix timestamp value in either seconds or milliseconds.
Remove the Expiry
We can also use GETEX
to remove any existing expiry associated with the key. We can do this with the PERSIST
option.
Let’s set the key again, but this time with an expiry:
SET composer "Mozart" EX 60
Result:
OK
And now let’s check its TTL:
TTL composer
Result:
(integer) 55
It currently has 55 seconds left before it expires.
Now let’s use GETEX
to get its value and remove its TTL:
GETEX composer PERSIST
Result:
"Mozart"
That shows us the key’s value. Behind the scenes, it removed the TTL associated with the key.
Now, let’s run the TTL command again:
TTL composer
Result:
(integer) -1
That tells us that there’s no expiry associated with the key. That’s because we removed the TTL with the PERSIST
option when we ran GETEX
.
Redis also has a separate PERSIST
command that removes the TTL from a key.