How to Use Redis as Cache: Simple Guide with Examples
To use
Redis as a cache, store data with SET commands and retrieve it with GET. Use expiration times with EXPIRE or SETEX to automatically remove stale data and keep cache fresh.Syntax
Redis caching mainly uses these commands:
SET key value [EX seconds]: Store a value with an optional expiration time in seconds.GET key: Retrieve the value stored at the key.DEL key: Remove a key and its value from cache.EXPIRE key seconds: Set or update expiration time for a key.
These commands let you save data temporarily and fetch it quickly.
redis
SET user:123 "John Doe" EX 300 GET user:123 DEL user:123 EXPIRE user:123 600
Example
This example shows how to cache a user's name for 5 minutes and then retrieve it.
redis
127.0.0.1:6379> SET user:1001 "Alice" EX 300 OK 127.0.0.1:6379> GET user:1001 "Alice" 127.0.0.1:6379> TTL user:1001 299
Output
"Alice"
Common Pitfalls
Common mistakes when using Redis as cache include:
- Not setting expiration time, causing stale data to stay forever.
- Using keys without a clear naming pattern, making management hard.
- Ignoring cache misses and not falling back to the original data source.
Always set expiration and handle missing keys gracefully.
redis
;; Wrong: No expiration set SET session:abc123 "data" ;; Right: Set expiration to 10 minutes SET session:abc123 "data" EX 600
Quick Reference
Remember these tips for effective Redis caching:
- Use
SET key value EX secondsto store data with expiration. - Use consistent key naming like
type:id(e.g.,user:1001). - Check for
GETreturningnulland reload data if needed. - Use
DELto clear cache when data changes.
Key Takeaways
Always set expiration on cached data to avoid stale entries.
Use clear, consistent key names for easy cache management.
Handle cache misses by fetching fresh data from the main source.
Use Redis commands SET, GET, EXPIRE, and DEL for caching operations.