You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Redis Pub/Sub (publish/subscribe) is a messaging pattern where publishers send messages to named channels and subscribers receive them in real time. Publishers and subscribers are decoupled — a publisher does not need to know how many subscribers are listening, and subscribers do not need to know who is publishing.
The model has three components:
When a publisher sends a message, Redis fans it out to every currently-connected subscriber on that channel. Messages are not persisted — if no subscriber is listening when a message is published, it is lost.
Open a second terminal and subscribe to a channel:
127.0.0.1:6379> SUBSCRIBE notifications
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "notifications"
3) (integer) 1
The client is now in subscriber mode and can only receive messages (no other commands).
In the first terminal, publish a message:
127.0.0.1:6379> PUBLISH notifications "New order placed: #1042"
(integer) 1 # number of subscribers that received the message
The subscriber terminal immediately displays:
1) "message"
2) "notifications"
3) "New order placed: #1042"
Subscribe to multiple channels matching a glob-style pattern:
127.0.0.1:6379> PSUBSCRIBE order.*
This matches channels such as order.created, order.shipped, and order.cancelled. Use PUNSUBSCRIBE to unsubscribe from patterns.
127.0.0.1:6379> UNSUBSCRIBE notifications
For durable, replayable message streams consider using Redis Streams (XADD / XREAD) instead.
# Live dashboard updates
127.0.0.1:6379> PUBLISH dashboard "metrics_updated"
# Chat application rooms
127.0.0.1:6379> PUBLISH room:general "alice: hello everyone"
# Cache invalidation across multiple app servers
127.0.0.1:6379> PUBLISH cache_invalidate "product:99"
Pub/Sub is an excellent fit for lightweight, real-time event broadcasting where at-most-once delivery is acceptable.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.