Database Management
Redis
Subjective
Oct 05, 2025
Explain Redis Pub/Sub messaging system with examples.
Detailed Explanation
Redis Pub/Sub enables message passing between publishers and subscribers:
**Basic Pub/Sub:**
# Subscribe to channels
SUBSCRIBE news sports weather
PSUBSCRIBE news:* # pattern subscription
# Publish messages
PUBLISH news "Breaking: Redis 7.0 released"
PUBLISH sports "Game result: Team A wins"
**Python Publisher:**
import redis
r = redis.Redis()
# Publish messages
r.publish('notifications', 'User logged in')
r.publish('alerts', 'High CPU usage detected')
**Python Subscriber:**
import redis
r = redis.Redis()
pubsub = r.pubsub()
# Subscribe to channels
pubsub.subscribe('notifications', 'alerts')
pubsub.psubscribe('user:*') # pattern subscription
# Listen for messages
for message in pubsub.listen():
if message['type'] == 'message':
print(f"Channel: {message['channel']}")
print(f"Data: {message['data']}")
**Use Cases:**
• Real-time notifications
• Chat applications
• Live updates
• Event broadcasting
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts