Unsubscribe with UNSUBSCRIBE
In this step, you will learn how to unsubscribe from a channel in Redis using the UNSUBSCRIBE command. Unsubscribing removes a client from the list of subscribers for a specific channel, preventing it from receiving further messages published to that channel.
Terminal 1: Exit Subscription Mode
Go to Terminal 1 (where you are currently subscribed to mychannel). You should see the subscription status showing "Reading messages... (press Ctrl-C to quit)".
Since Terminal 1 is in subscription mode, you cannot execute regular Redis commands directly. To unsubscribe, you need to exit the subscription mode first:
-
Press Ctrl+C to exit the subscription mode
-
You should see that the redis-cli session ends and returns to the terminal prompt
-
Reconnect to Redis:
redis-cli
-
Now you can execute the UNSUBSCRIBE command (though it's not necessary since disconnecting already unsubscribed you):
UNSUBSCRIBE mychannel
Note: When you pressed Ctrl+C, you actually already disconnected from all subscriptions. The UNSUBSCRIBE command is shown for demonstration purposes, but in practice, disconnecting automatically unsubscribes you from all channels.
The output in Terminal 1 will look like this:
1) "unsubscribe"
2) "mychannel"
3) (integer) 0
Let's break down the output:
"unsubscribe": This indicates that you have unsubscribed from a channel.
"mychannel": This is the name of the channel you unsubscribed from.
(integer) 0: This is the number of channels you are currently subscribed to. It's now 0 because you unsubscribed from mychannel.
Terminal 2: Test Publishing After Unsubscribe
Now switch to Terminal 2 and publish another message to mychannel:
PUBLISH mychannel "Is anyone still there?"
The output in Terminal 2 will be:
(integer) 0
This indicates that no clients received the message because you unsubscribed from the channel in Terminal 1.
Verify No Message Received
Look at Terminal 1 - you should notice that no new message appears because you have unsubscribed from the channel.
This demonstrates how unsubscribing from a channel prevents you from receiving further messages published to that channel, while the publisher can still send messages (but no one will receive them).
Important: Keep both terminals and their redis-cli sessions active for the next step.