In Redis, the SETEX
command sets a key to hold a given string value, and sets that key to time out after a given number of seconds.
Note: The SET
command can do the same thing, and it’s possible that the SETEX
command may be deprecated at some point. Therefore, it’s probably a good idea to use SET
instead of SETEX
if possible.
Syntax
The syntax for SETEX
goes like this:
SETEX key seconds value
Where key
is the key to set, seconds
is the number of seconds before it expires, and value
is the value to set.
It’s the equivalent of the following:
SET mykey value
EXPIRE mykey seconds
Which is basically the same as doing this:
SET mykey value EX seconds
Example
Here’s a simple example to demonstrate:
SETEX lunch 30 "Pad Thai"
Result:
OK
Now, if I’m quick and use GET
to return the value before the 30 seconds is up, I can see the value:
GET lunch
Result:
"Pad Thai"
But if I wait until after the 30 seconds is up, I get a null result:
GET lunch
Result:
(nil)
As mentioned, we can do the same thing with the SET
command, so it’s probably better to use that in case SETEX
is deprecated at some point.
There’s also a PSETEX
command that does the same thing as SETEX
, except that PSETEX
uses milliseconds.