What is Pub Sub in Redis: Simple Explanation and Example
Pub Sub (Publish-Subscribe) is a messaging system where senders (publishers) send messages to channels without knowing who will receive them, and receivers (subscribers) listen to channels to get messages. It allows real-time communication between different parts of an application without direct connections.How It Works
Imagine a radio station broadcasting music. The station is the publisher, and listeners are subscribers who tune in to the station's channel. In Redis Pub Sub, publishers send messages to named channels, and subscribers listen to those channels to receive messages instantly.
This system works without the publisher needing to know who the subscribers are. Messages are sent to channels, and all subscribers to those channels get the messages in real time. This makes it easy to build features like chat apps, live notifications, or real-time updates.
Example
This example shows how one client subscribes to a channel and another client publishes a message to that channel.
# In one terminal, subscribe to channel "news" redis-cli SUBSCRIBE news # In another terminal, publish a message to "news" redis-cli PUBLISH news "Hello subscribers!"
When to Use
Use Redis Pub Sub when you need fast, real-time communication between different parts of your app without storing messages. It is great for chat systems, live notifications, real-time analytics, or broadcasting events to many clients.
However, it does not store messages if no one is listening, so it is not suitable for guaranteed message delivery or message queues.
Key Points
- Pub Sub in Redis allows message broadcasting via channels.
- Publishers send messages without knowing subscribers.
- Subscribers receive messages instantly when subscribed.
- It is useful for real-time apps but does not store messages.