Pattern Subscribe with PSUBSCRIBE
In this step, you will learn how to subscribe to channels using patterns with the PSUBSCRIBE
command in Redis. PSUBSCRIBE
allows you to subscribe to multiple channels that match a specified pattern. This is useful when you want to receive messages from a group of related channels without subscribing to each one individually.
Open a terminal.
Connect to the Redis server using the redis-cli
command:
redis-cli
Now, subscribe to channels matching the pattern news.*
using the PSUBSCRIBE
command:
PSUBSCRIBE news.*
The output will look similar to this:
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "news.*"
3) (integer) 1
Let's break down the output:
"psubscribe"
: This indicates that you have successfully subscribed to a pattern.
"news.*"
: This is the pattern you subscribed to. The .*
is a wildcard that matches any characters.
(integer) 1
: This is the number of patterns you are currently subscribed to.
Keep this terminal open and subscribed.
Now, exit the redis-cli
in this terminal.
exit
Open a new terminal and connect to Redis:
redis-cli
Publish a message to the news.sports
channel using the PUBLISH
command:
PUBLISH news.sports "Sports news update!"
The output in this terminal will be the number of subscribers that received the message:
(integer) 1
Now, exit the redis-cli
in this terminal.
exit
Switch back to the first terminal (where you subscribed to the pattern). You should see the message you just published. If you closed that terminal, you'll need to open a new terminal and re-subscribe to news.*
using the PSUBSCRIBE news.*
command.
redis-cli
PSUBSCRIBE news.*
Keep this terminal open and subscribed.