How to Use PSUBSCRIBE in Redis for Pattern-Based Pub/Sub
Use the
PSUBSCRIBE command in Redis to subscribe to channels matching a pattern. It listens to all channels that fit the pattern and receives messages published to them, enabling flexible message handling.Syntax
The PSUBSCRIBE command subscribes the client to channels matching given patterns. Each pattern can include wildcards like * to match multiple channels.
PSUBSCRIBE <pattern> [<pattern> ...]: Subscribe to one or more channel patterns.- Patterns support
*as a wildcard for any characters. - Once subscribed, the client receives messages from all matching channels.
redis
PSUBSCRIBE pattern1 pattern2 ...
Example
This example shows how to subscribe to all channels starting with news. using PSUBSCRIBE. The client will receive messages from news.sports, news.weather, etc.
redis
redis-cli > PSUBSCRIBE news.* Reading messages... (press Ctrl-C to quit) 1) "psubscribe" 2) "news.*" 3) (integer) 1 # In another terminal: redis-cli > PUBLISH news.sports "Sports update" (integer) 1 # Back to subscriber terminal: 1) "pmessage" 2) "news.*" 3) "news.sports" 4) "Sports update"
Output
1) "psubscribe"
2) "news.*"
3) (integer) 1
1) "pmessage"
2) "news.*"
3) "news.sports"
4) "Sports update"
Common Pitfalls
Common mistakes when using PSUBSCRIBE include:
- Trying to use
PSUBSCRIBEin a pipeline or transaction, which is not supported. - Not handling the subscription messages properly, which include subscription confirmations.
- Confusing
SUBSCRIBE(exact channels) withPSUBSCRIBE(pattern matching). - Expecting
PSUBSCRIBEto return immediately; it blocks and listens for messages.
redis
Wrong usage example: redis-cli > MULTI > PSUBSCRIBE news.* > EXEC Right usage: redis-cli > PSUBSCRIBE news.*
Quick Reference
| Command | Description |
|---|---|
| PSUBSCRIBE | Subscribe to channels matching the pattern |
| PUNSUBSCRIBE [pattern] | Unsubscribe from pattern subscriptions |
| PUBLISH | Send message to a channel |
| SUBSCRIBE | Subscribe to exact channel names |
Key Takeaways
Use PSUBSCRIBE to listen to multiple channels matching a pattern with wildcards.
PSUBSCRIBE blocks the client and delivers messages from all matching channels.
Do not use PSUBSCRIBE inside transactions or pipelines.
Handle subscription confirmation messages to manage your subscriptions properly.
Use PUNSUBSCRIBE to stop listening to pattern subscriptions.