Real-Time Messaging with Pub/Sub
Intermediate12 min
Implement real-time event broadcasting using Redis publish/subscribe channels for decoupled microservice communication.
Prerequisites
- -Redis installed and running
- -Two terminal windows for publisher and subscriber
Steps
1
Start a subscriber on a channel
Open a terminal and subscribe to a named channel to listen for messages.
$ redis-cli SUBSCRIBE notifications
The subscriber blocks and waits for messages. You will need a second terminal for the publisher.
2
Publish a message to the channel
In a second terminal, send a message to all subscribers on the channel.
$ redis-cli PUBLISH notifications '{"event":"user.signup","userId":1001}'
3
Subscribe with pattern matching
Use PSUBSCRIBE to listen to multiple channels matching a glob pattern.
$ redis-cli PSUBSCRIBE 'events.*'
This matches events.user, events.order, events.payment, etc.
4
Publish to a patterned channel
Send a message to a specific channel that pattern subscribers will receive.
$ redis-cli PUBLISH events.order '{"orderId":5001,"status":"created"}'
5
Check active channels and subscribers
Inspect which pub/sub channels are currently active.
$ redis-cli PUBSUB CHANNELS '*'
Full Script
FAQ
Discussion
Loading comments...