Key commands, syntax, and examples for Redis Publish-Subscribe
1. SUBSCRIBE
Subscribes to one or more channels to receive messages from those channels.
Syntax:
SUBSCRIBE channel [channel …]
Example:
SUBSCRIBE news sports
Output:
subscribe news subscribe sports
2. UNSUBSCRIBE
Unsubscribes from one or more channels. If no channels are provided, the client unsubscribes from all channels.
Syntax:
UNSUBSCRIBE [channel …]
Example:
UNSUBSCRIBE news sports
Output:
unsubscribe news unsubscribe sports
3. PUBLISH
Publishes a message to a specific channel, and all subscribers to that channel receive the message.
Syntax:
PUBLISH channel message
Example:
PUBLISH news “Breaking news: Redis is awesome!”
Output:
(integer) 1 (The number of subscribers to the channel)
4. PSUBSCRIBE
Subscribes to channels based on a pattern. It allows subscribing to multiple channels that match the specified pattern.
Syntax:
PSUBSCRIBE pattern [pattern …]
Example:
PSUBSCRIBE news.*
Output:
psubscribe news.*
5. PUNSUBSCRIBE
Unsubscribes from channels matching the specified pattern(s).
Syntax:
PUNSUBSCRIBE [pattern …]
Example:
PUNSUBSCRIBE news.*
Output:
punsubscribe news.*
6. PUBSUB CHANNELS
Lists the active channels matching the optional pattern.
Syntax:
PUBSUB CHANNELS [pattern]
Example:
PUBSUB CHANNELS news sports*
Output:
news sports
7. PUBSUB NUMSUB
Returns the number of subscribers for one or more specified channels.
Syntax:
PUBSUB NUMSUB [channel …]
Example:
PUBSUB NUMSUB news sports
Output:
1 1
Complete Guide to Redis Publish Subscribe
Redis Publish-Subscribe (Pub/Sub) is a messaging pattern in Redis that allows one-to-many communication. It involves publishers and subscribers, where publishers send messages (also known as “events“) to channels, and subscribers receive messages from channels they are interested in. Pub/Sub is used for building real-time applications, message broadcasting, and event-driven architectures.
Important Topics for Redis Publish Subscribe
- Key Concepts and Components
- How Redis Pub/Sub Works?
- Use Cases for Redis Pub/Sub
- Benefits for Redis Pub/Sub
- Key commands, syntax, and examples for Redis Publish-Subscribe
- Redis Pub/Sub Applications:
- How Redis Publish Subscribe works in Chat Applications?
- Conclusion