Redis
Pub/Sub
Broadcast messages to subscribed clients.
By EZ4Code Team
pubsubmessagingbroadcast
Code
# Subscriber (terminal 1)
SUBSCRIBE news alerts
PSUBSCRIBE log:*
# Publisher (terminal 2)
PUBLISH news "Server restarted"
PUBLISH log:error "Disk 80% full"
# Message format on subscriber:
# 1) "message"
# 2) "news"
# 3) "Server restarted"
# Pattern subscribe to all log:* channels
# PSUBSCRIBE log:*
# Lists vs pub/sub for durable queues:
# LPUSH + BRPOP keeps messages if no consumer is listeningExplanation
Redis pub/sub delivers messages to all connected subscribers in real time, with no persistence if no one is listening. SUBSCRIBE matches exact channels while PSUBSCRIBE matches glob patterns. For durable messaging, use lists or streams (XADD/XREAD) instead of pub/sub.
More Redis Snippets
Strings & Counters
Set, get, increment, and expire string values.
Lists & Queues
Build queues and stacks with list operations.
Hashes
Store object fields and values efficiently.
Sets
Manage unique collections and compute intersections.
Sorted Sets & Leaderboards
Rank items by score for leaderboards and scheduling.
Persistence
Configure RDB snapshots and AOF append logs.