Redis Pub/Sub

Pub/Sub is a messaging communication pattern. This lesson covers Redis publish/subscribe functionality.

What is Pub/Sub?

Pub/Sub pattern consists of:

Publisher → Channel → Subscriber 1
                    → Subscriber 2
                    → Subscriber 3

Basic Commands

SUBSCRIBE: Subscribe to a Channel

REDIS
# Subscribe to a single channel
SUBSCRIBE channel1

# Subscribe to multiple channels
SUBSCRIBE channel1 channel2 channel3

After subscribing, the client enters a waiting state to receive messages.

PUBLISH: Publish a Message

REDIS
# Publish a message to a channel
PUBLISH channel1 "Hello, Redis!"
(integer) 2  # Returns the number of subscribers that received the message

UNSUBSCRIBE: Unsubscribe

REDIS
# Unsubscribe from all channels
UNSUBSCRIBE

# Unsubscribe from a specific channel
UNSUBSCRIBE channel1

Pattern Subscription

PSUBSCRIBE: Pattern-Matched Subscription

REDIS
# Subscribe to channels matching a pattern
PSUBSCRIBE news.*  # Subscribe to all channels starting with news.

# Example
PSUBSCRIBE user:*:notifications  # Subscribe to all user notification channels

PUNSUBSCRIBE: Cancel Pattern Subscription

REDIS
# Cancel all pattern subscriptions
PUNSUBSCRIBE

# Cancel a specific pattern subscription
PUNSUBSCRIBE news.*

Use Cases

1. Real-Time Message Push

Example: Real-Time Notifications

BASH
# Terminal 1: subscribe to notifications
SUBSCRIBE notifications

# Terminal 2: publish a notification
PUBLISH notifications "New user registered"
▶ Try it Yourself

2. Chat Room

Example: Chat Room

BASH
# User 1: subscribe to chat room
SUBSCRIBE chatroom:general

# User 2: send a message
PUBLISH chatroom:general "Hello everyone!"
▶ Try it Yourself

3. System Notifications

Example: System Alerts

BASH
# Admin: subscribe to system alerts
SUBSCRIBE system:alerts

# System: send an alert
PUBLISH system:alerts "High CPU usage detected"
▶ Try it Yourself

Message Format

Message format received by subscribers:

TEXT
1) "message"           # Message type
2) "channel1"          # Channel name
3) "Hello, Redis!"     # Message content

Pattern subscription message format:

TEXT
1) "pmessage"          # Message type
2) "news.*"            # Subscribed pattern
3) "news:sports"       # Actual channel name
4) "Game result!"      # Message content

Important Notes

⚠️ Messages are not persisted: Pub/Sub messages are not stored. Subscribers only receive messages sent after they subscribe.

⚠️ Message loss: If a subscriber disconnects, messages sent during that period are lost.

💡 Alternative: When message persistence is needed, use Redis Streams or Lists for message queues.

Introduced in Redis 5.0, Streams are a better message queue solution:

REDIS
# Add a message
XADD mystream * name "Alice" action "login"
"1638361451780-0"

# Read messages
XREAD COUNT 1 STREAMS mystream 0

# Consumer groups
XGROUP CREATE mystream mygroup 0
XREADGROUP GROUP mygroup consumer1 COUNT 1 STREAMS mystream >

Stream vs Pub/Sub

Feature Pub/Sub Stream
Message persistence ❌ Not persisted ✅ Persisted
Message acknowledgment ❌ No ACK ✅ ACK supported
Consumer groups ❌ Not supported ✅ Supported
Historical messages ❌ Cannot retrieve ✅ Queryable
Use case Real-time notifications Message queues

❓ FAQ

Q Are Pub/Sub messages stored?
A No. Pub/Sub is "fire and forget" — messages are not persisted.
Q Can a disconnected subscriber receive historical messages?
A No. Use Streams or Lists for message persistence.
Q How many subscribers can a channel have?
A Theoretically unlimited — depends on server performance.

📖 Summary

📝 Exercises

  1. Subscription practice: Use two terminals — one subscribes, the other publishes
  2. Pattern subscription: Use PSUBSCRIBE to subscribe to multiple matching channels
  3. Stream practice: Use XADD/XREAD to implement a simple message queue

Next Lesson

In the next lesson, we will learn Redis Transactions, covering transaction usage and caveats.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏