How to Use SUBSCRIBE Command in Redis for Pub/Sub Messaging
SUBSCRIBE command to listen for messages published to one or more channels. When subscribed, Redis sends messages to the client whenever a PUBLISH command is executed on those channels. This allows real-time message delivery between clients.Syntax
The SUBSCRIBE command syntax is simple:
SUBSCRIBE <channel> [channel2 channel3 ...]
Here, <channel> is the name of the channel you want to listen to. You can subscribe to multiple channels by listing them separated by spaces.
Once subscribed, the client enters a listening mode and receives messages published to those channels.
SUBSCRIBE channel1 channel2
Example
This example shows how to subscribe to a channel named news and receive messages published to it.
redis-cli
> SUBSCRIBE news
# In another terminal:
redis-cli
> PUBLISH news "Hello subscribers!"Common Pitfalls
1. Blocking Mode: After issuing SUBSCRIBE, the client is blocked and can only receive messages. It cannot run other commands until unsubscribed.
2. Wrong Client Type: Using SUBSCRIBE on a client that expects normal command responses can cause confusion because the client enters a special message-receiving mode.
3. Forgetting to Unsubscribe: If you want to stop listening, you must use UNSUBSCRIBE or close the connection.
Wrong way: redis-cli > SUBSCRIBE news > SET key value # This will not work because client is blocked Right way: redis-cli > SUBSCRIBE news # Use a separate client to run other commands
Quick Reference
| Command | Description |
|---|---|
| SUBSCRIBE | Subscribe to one or more channels to receive messages. |
| UNSUBSCRIBE [channel [channels...]] | Unsubscribe from channels or all if none specified. |
| PUBLISH | Send a message to all subscribers of the channel. |
| PSUBSCRIBE | Subscribe to channels matching patterns. |
| PUNSUBSCRIBE [pattern [patterns...]] | Unsubscribe from pattern subscriptions. |
Key Takeaways
SUBSCRIBE to listen for messages on specified Redis channels.UNSUBSCRIBE to stop receiving messages or close the connection.SUBSCRIBE.