Using Publish/Subscribe messaging with Redis™
The Publish/Subscribe feature is available with Redis™ 6 and 7.
Pub/Sub is a highly scalable messaging model fit to handle large amounts of data and that enables asynchronous communication on low bandwidth.
The model decouples the publishers, the clients sending a message, from the subscribers, the one or several clients receiving the message. Messages are published to a third component, the message broker, whose job is to forward messages from publishers to subscribers under topics.
Topics describe the data contained within messages, allowing subscribers to choose which messages to receive based on the subject of the topic. For example, under a topic named
/weather-paris one could expect to find data about the weather in Paris.
To implement Pub/Sub using Redis, you can run commands such as
You may need certain IAM permissions to carry out some actions described on this page. This means:
- Connect to your Redis™ Database Instance.
- Subscribe to a topic. In this tutorial, we will use
temperatureas an example of topic.> SUBSCRIBE temperatureReading messages... (press Ctrl-C to quit)1) "subscribe"2) "myqueue"3) (integer) 1
- Publish to the topic in a separate client. You can connect to the same Redis™ Database Instance in a different terminal to do so.
> PUBLISH temperature monday/12C(integer) 1
- Read the message in the first terminal, where you are subscribed to the
temperaturetopic. You can see the update in real-time.All other subscribers of the> SUBSCRIBE temperature1) "subscribe"2) "temperature"3) (integer) 11) "message"2) "temperature"3) "monday/12C"
temperaturetopic will receive the same messages.
Refer to the official Redis Pub/Sub documentation page for more commands and use-cases.