How to Use SETEX Command in Redis for Expiring Keys
Use the
SETEX command in Redis to set a key with a value and an expiration time in seconds. The syntax is SETEX key seconds value, which stores the key and automatically deletes it after the given time.Syntax
The SETEX command syntax is:
- key: The name of the key you want to set.
- seconds: The time in seconds before the key expires and is deleted.
- value: The value to store in the key.
This command sets the key with the value and ensures it will be removed after the specified time.
redis
SETEX key seconds value
Example
This example shows how to set a key named session_token with the value abc123 that expires after 60 seconds.
redis
SETEX session_token 60 abc123
GET session_tokenOutput
OK
"abc123"
Common Pitfalls
Common mistakes when using SETEX include:
- Setting the expiration time to 0 or a negative number, which is invalid.
- Using
SETEXwith a non-integer expiration time. - Expecting the key to persist after expiration time; it will be deleted automatically.
Also, SETEX replaces the value and expiration if the key already exists.
redis
/* Wrong: expiration time zero */ SETEX mykey 0 value /* Right: positive expiration time */ SETEX mykey 30 value
Output
ERR invalid expire time in SETEX
OK
Quick Reference
Remember these points when using SETEX:
- Use seconds as expiration time.
- Key is set with value and expiration in one command.
- Key is deleted automatically after expiration.
- Overwrites existing key and expiration.
Key Takeaways
SETEX sets a key with a value and expiration time in seconds in one command.
Expiration time must be a positive integer; zero or negative values cause errors.
The key is automatically deleted after the expiration time passes.
Using SETEX on an existing key overwrites its value and expiration time.
Check the expiration time carefully to avoid unexpected key deletions.