Pub/Sub messaging in Redis
Pub/Sub messaging is a messaging pattern in Redis that allows multiple clients to communicate with each other through a central messaging system. In Pub/Sub, clients are divided into two categories: publishers and subscribers. Publishers send messages to channels, while subscribers receive messages from channels they have subscribed to.
Here's an example of how Pub/Sub messaging works in Redis:
- A publisher sends a message to a channel:
PUBLISH my-channel "Hello, World!"
- A subscriber subscribes to the same channel:
SUBSCRIBE my-channel
- The subscriber receives the message sent by the publisher:
1) "message"
2) "my-channel"
3) "Hello, World!"
This shows that the subscriber has received the message "Hello, World!" from the channel "my-channel".
You can also have multiple subscribers on the same channel. In this case, each subscriber will receive a copy of the message when it is sent:
SUBSCRIBE my-channel
1) "message"
2) "my-channel"
3) "Hello, World!"
1) "message"
2) "my-channel"
3) "Hello, World!"
In addition to publishing and subscribing to channels, Redis also supports pattern-based subscriptions. A pattern-based subscription allows a subscriber to receive messages that match a specific pattern. For example, a subscriber could subscribe to all channels that start with "news." like this:
PSUBSCRIBE news.*
Then, when a message is published to a channel that matches the pattern, the subscriber will receive the message:
1) "pmessage"
2) "news.*"
3) "news.sports"
4) "Hello, Sports Fans!"
This shows that the subscriber has received the message "Hello, Sports Fans!" from the channel "news.sports", which matches the pattern "news.*".
Leave a Comment