Pattern Subscriptions
Pattern subscriptions
Section titled “Pattern subscriptions”PSUBSCRIBE works like SUBSCRIBE but accepts a glob pattern instead of a literal channel name. A single PSUBSCRIBE call can therefore match dozens of channels at once without listing each one individually.
The three glob wildcards Redis supports are:
| Pattern | Meaning |
|---|---|
* | Match any sequence of characters (including none) |
? | Match exactly one character |
[abc] | Match one character from the set — e.g. [abc] matches a, b, or c |
For example, news.* matches news.sports, news.tech, news.finance, and any other channel that begins with news..
PSUBSCRIBE demo
Section titled “PSUBSCRIBE demo”The interaction below uses two terminals. Terminal 1 subscribes with a pattern; Terminal 2 publishes to several channels.
-- Terminal 1 --127.0.0.1:6379> PSUBSCRIBE news.*Reading messages... (press Ctrl-C to quit)1) "psubscribe"2) "news.*"3) (integer) 1
-- Terminal 2 --127.0.0.1:6379> PUBLISH news.sports "score update"(integer) 1127.0.0.1:6379> PUBLISH news.tech "new release"(integer) 1
-- Terminal 1 receives --1) "pmessage"2) "news.*"3) "news.sports"4) "score update"1) "pmessage"2) "news.*"3) "news.tech"4) "new release"Notice the reply format: pmessage delivers four parts — the event type, the matched pattern, the actual channel, and the payload. This is different from a plain message reply, which only has three parts.
PUBLISH news.sports "score update"
PUBLISH news.tech "new release"
PUBLISH weather.today "sunny"PUNSUBSCRIBE
Section titled “PUNSUBSCRIBE”PUNSUBSCRIBE pattern removes a pattern subscription. Calling it with no argument unsubscribes from all active patterns.
127.0.0.1:6379> PUNSUBSCRIBE news.*1) "punsubscribe"2) "news.*"3) (integer) 0The third element is the count of remaining pattern subscriptions. When it reaches 0 the client exits pattern-subscribe mode and can issue regular commands again.
Keyspace notifications (teaser)
Section titled “Keyspace notifications (teaser)”Redis itself uses the Pub/Sub mechanism internally to emit events about keyspace activity. When enabled, Redis publishes to special built-in channels such as:
__keyevent@0__:expired— fires whenever a key in database 0 expires__keyspace@0__:mykey— fires whenever any command touchesmykey
You can enable these notifications with:
127.0.0.1:6379> CONFIG SET notify-keyspace-events KEAOKThen subscribe with PSUBSCRIBE __keyevent@0__:* to catch every keyspace event on database 0. This is an advanced pattern useful for cache invalidation and audit logging — a deeper dive belongs in its own lesson.