0
0
Redisquery~5 mins

Temporary data with TTL in Redis

Choose your learning style9 modes available
Introduction
Sometimes you want to store data that only lasts for a short time and then disappears automatically. This helps keep your database clean and saves space.
Storing user session information that expires after a few minutes.
Caching web page data to speed up loading but refresh it regularly.
Saving one-time verification codes that should expire quickly.
Keeping temporary flags or counters that reset after some time.
Syntax
Redis
SET key value EX seconds
The EX option sets the expiration time in seconds.
After the time runs out, the key is deleted automatically.
Examples
Stores 'user_data' in 'session123' key that expires in 300 seconds (5 minutes).
Redis
SET session123 user_data EX 300
Stores a temporary code that expires in 60 seconds.
Redis
SET temp_code 123456 EX 60
Caches a web page for 1 hour.
Redis
SET cache_page "<html>...</html>" EX 3600
Sample Program
This sets a temporary login token that expires in 120 seconds, then retrieves its value and remaining time to live.
Redis
SET login_token abcdef EX 120
GET login_token
TTL login_token
OutputSuccess
Important Notes
If you try to GET a key after it expires, Redis returns nil (no value).
You can check how many seconds remain before expiration using TTL command.
Setting a key without EX means it will stay forever unless deleted manually.
Summary
Use SET with EX to store temporary data that expires automatically.
TTL helps you see how long the data will last.
Temporary data keeps your database clean and efficient.