Redis není jen key-value store. Cache, sessions, rate limiting, pub/sub, leaderboards — versatilní in-memory databáze.
Cache pattern¶
import redis r = redis.Redis() def get_user(user_id):
Check cache¶
cached = r.get(f”user:{user_id}”) if cached: return json.loads(cached)
Cache miss — fetch from DB¶
user = db.users.find_one(user_id) r.setex(f”user:{user_id}”, 3600, json.dumps(user)) # TTL 1h return user
Rate limiter¶
def rate_limit(key, limit=100, window=60): pipe = r.pipeline() now = time.time() pipe.zremrangebyscore(key, 0, now - window) pipe.zadd(key, {str(now): now}) pipe.zcard(key) pipe.expire(key, window) _, _, count, _ = pipe.execute() return count <= limit
Pub/Sub¶
Publisher¶
r.publish(‘notifications’, json.dumps({‘user’: 123, ‘msg’: ‘Hello’}))
Subscriber¶
pubsub = r.pubsub() pubsub.subscribe(‘notifications’) for message in pubsub.listen(): if message[‘type’] == ‘message’: handle(json.loads(message[‘data’]))
Klíčový takeaway¶
Cache s TTL, sorted set pro rate limiting, pub/sub pro real-time. Redis = Swiss Army knife.