0
0
RedisHow-ToBeginner · 3 min read

How to Use SUBSCRIBE Command in Redis for Pub/Sub Messaging

In Redis, use the 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.

redis
SUBSCRIBE channel1 channel2
💻

Example

This example shows how to subscribe to a channel named news and receive messages published to it.

redis
redis-cli
> SUBSCRIBE news

# In another terminal:
redis-cli
> PUBLISH news "Hello subscribers!"
Output
Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "news" 3) (integer) 1 1) "message" 2) "news" 3) "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.

redis
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

CommandDescription
SUBSCRIBE [channels...]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 [patterns...]Subscribe to channels matching patterns.
PUNSUBSCRIBE [pattern [patterns...]]Unsubscribe from pattern subscriptions.

Key Takeaways

Use SUBSCRIBE to listen for messages on specified Redis channels.
After subscribing, the client is blocked and only receives messages until unsubscribed.
Use separate clients for publishing messages and running other commands.
Remember to UNSUBSCRIBE to stop receiving messages or close the connection.
You can subscribe to multiple channels at once by listing them after SUBSCRIBE.