Redis: Redis Examples
Redis Examples
1. Cache Application
▶ Example
Basic cache operations:
BASH
127.0.0.1:6379> SET cache:user:1 '{"name":"Alice","age":25}'
OK
127.0.0.1:6379> EXPIRE cache:user:1 3600
(integer) 1
127.0.0.1:6379> GET cache:user:1
'{"name":"Alice","age":25}'
127.0.0.1:6379> DEL cache:user:1
(integer) 1
❓ FAQ
Q Is Redis suitable for caching?
A Very suitable. Redis is memory-based with extremely fast read/write, supports expiration and eviction policies, making it ideal for caching.
Q How to implement distributed locks in Redis?
A Use the SET command with NX and EX parameters:
SET lock:resource "locked" NX EX 10 to atomically acquire a lock and set expiration.Q Why is the KEYS command disabled in production?
A KEYS scans the entire keyspace and can block the server with large datasets. Use the SCAN command for incremental iteration instead.
📖 Summary
- Redis can be used for caching, queues, leaderboards, rate limiting and more
- String type is suitable for caching and counters
- Hash type is suitable for storing objects and shopping carts
- List type is suitable for message queues
- Set type is suitable for social relations and tags
- Sorted set type is suitable for leaderboards
📝 Exercises
- Cache exercise: Implement a user info cache with 1-hour expiration
- Counter exercise: Implement an article view counter with increment and get
- Leaderboard exercise: Use sorted set to implement a game leaderboard with score updates and rank queries