How to Use Redis for Session Cache: Simple Guide
Use
Redis to store session data by saving session IDs as keys and session information as values. Set expiration times on keys to automatically clear old sessions, enabling fast and scalable session management.Syntax
To use Redis for session caching, you typically set a session key with a value and an expiration time, then get the session data using the key.
SET key value EX seconds: Stores session data with expiration.GET key: Retrieves session data.DEL key: Deletes session data.
redis
SET session:<session_id> <session_data> EX <expiration_seconds> GET session:<session_id> DEL session:<session_id>
Example
This example shows how to save a user session with a 30-minute expiration, retrieve it, and delete it using Redis commands.
redis
127.0.0.1:6379> SET session:12345 "{\"user_id\":1,\"role\":\"admin\"}" EX 1800 OK 127.0.0.1:6379> GET session:12345 "{\"user_id\":1,\"role\":\"admin\"}" 127.0.0.1:6379> DEL session:12345 (integer) 1
Output
OK
"{\"user_id\":1,\"role\":\"admin\"}"
(integer) 1
Common Pitfalls
Common mistakes when using Redis for session cache include:
- Not setting expiration time, causing sessions to never expire and fill memory.
- Using non-unique keys, which can overwrite sessions.
- Storing large session data, which slows Redis performance.
Always use unique session keys and set reasonable expiration.
redis
/* Wrong: No expiration set, sessions never expire */ SET session:12345 "data" /* Right: Set expiration to 30 minutes (1800 seconds) */ SET session:12345 "data" EX 1800
Quick Reference
| Command | Description |
|---|---|
| SET key value EX seconds | Store session data with expiration time |
| GET key | Retrieve session data by key |
| DEL key | Delete session data by key |
| EXPIRE key seconds | Set or update expiration time on existing key |
Key Takeaways
Always set expiration on session keys to avoid memory bloat.
Use unique keys like 'session:' to prevent collisions.
Keep session data small for fast Redis performance.
Use Redis commands SET, GET, and DEL to manage sessions simply.
Redis is fast and scalable for session caching in web apps.