0
0
Redisquery~5 mins

PSUBSCRIBE for pattern matching in Redis

Choose your learning style9 modes available
Introduction
PSUBSCRIBE lets you listen to many channels at once by using patterns instead of exact names. This helps you get messages from groups of channels easily.
You want to get messages from all channels that start with 'news.'.
You want to listen to channels that end with '.updates'.
You want to monitor all channels containing the word 'chat'.
You want to subscribe to channels with similar names without listing each one.
You want to build a notification system that reacts to many related channels.
Syntax
Redis
PSUBSCRIBE pattern [pattern ...]
Patterns can include '*' to match any number of characters.
You can subscribe to multiple patterns at once by listing them.
Examples
Subscribe to all channels starting with 'news.'.
Redis
PSUBSCRIBE news.*
Subscribe to all channels ending with '.updates'.
Redis
PSUBSCRIBE *.updates
Subscribe to all channels containing 'chat' anywhere.
Redis
PSUBSCRIBE *chat*
Subscribe to channels starting with 'sports.' and 'news.'.
Redis
PSUBSCRIBE sports.* news.*
Sample Program
This example shows subscribing to all channels starting with 'news.'. Messages published to 'news.sports' and 'news.weather' will be received. Messages to 'chat.general' will not.
Redis
redis-cli
PSUBSCRIBE news.*

# Then in another terminal:
redis-cli
PUBLISH news.sports "Sports news here"
PUBLISH news.weather "Weather news here"
PUBLISH chat.general "Hello chat"

# The subscriber will receive messages only from channels matching 'news.*'
OutputSuccess
Important Notes
PSUBSCRIBE uses pattern matching with '*' as a wildcard for any characters.
Time complexity depends on the number of patterns and channels but is efficient for typical use.
Common mistake: Using PSUBSCRIBE when you want exact channel names; use SUBSCRIBE instead.
Use PSUBSCRIBE when you want to listen to many related channels without listing each one.
Summary
PSUBSCRIBE listens to channels matching patterns with wildcards.
It helps receive messages from groups of channels easily.
Use '*' in patterns to match any characters.