How to Use UNSUBSCRIBE Command in Redis Pub/Sub
In Redis, use the
UNSUBSCRIBE command to stop listening to one or more channels in the Pub/Sub messaging system. This command removes the subscription and stops messages from those channels from being delivered to the client.Syntax
The UNSUBSCRIBE command syntax is simple. You write UNSUBSCRIBE followed by zero or more channel names. If no channels are specified, it unsubscribes from all channels the client is currently subscribed to.
- UNSUBSCRIBE [channel1 channel2 ...]: Unsubscribe from the listed channels.
- If no channels are given, unsubscribe from all.
redis
UNSUBSCRIBE [channel1 channel2 ...]
Example
This example shows a client subscribing to two channels, then unsubscribing from one channel, and finally unsubscribing from all channels.
redis
SUBSCRIBE news sports # Client receives messages from 'news' and 'sports' UNSUBSCRIBE news # Client stops receiving messages from 'news' but still receives from 'sports' UNSUBSCRIBE # Client unsubscribes from all remaining channels (here, 'sports')
Output
# Output when subscribing:
# subscribe to news
# subscribe to sports
# Output when unsubscribing from 'news':
# unsubscribe from news
# Output when unsubscribing from all:
# unsubscribe from sports
Common Pitfalls
One common mistake is calling UNSUBSCRIBE without specifying channels when you only want to unsubscribe from some channels; this will unsubscribe from all channels instead. Another is forgetting that UNSUBSCRIBE only works if the client is currently subscribed to the channels; otherwise, it has no effect.
Also, UNSUBSCRIBE does not close the connection; the client can still subscribe again later.
redis
UNSUBSCRIBE # This unsubscribes from all channels, not just one # Correct way to unsubscribe from specific channels: UNSUBSCRIBE news sports
Quick Reference
| Command | Description |
|---|---|
| SUBSCRIBE channel1 [channel2 ...] | Subscribe to one or more channels |
| UNSUBSCRIBE [channel1 channel2 ...] | Unsubscribe from specified channels or all if none specified |
| PSUBSCRIBE pattern1 [pattern2 ...] | Subscribe to channels matching patterns |
| PUNSUBSCRIBE [pattern1 pattern2 ...] | Unsubscribe from patterns or all if none specified |
Key Takeaways
Use
UNSUBSCRIBE to stop receiving messages from specific or all channels in Redis Pub/Sub.If no channels are specified,
UNSUBSCRIBE removes all subscriptions for the client.UNSUBSCRIBE does not close the connection; you can subscribe again anytime.Always specify channels if you want to unsubscribe selectively to avoid unsubscribing from all.
The client must be subscribed to channels for
UNSUBSCRIBE to have an effect.