How to Use PUBLISH Command in Redis for Messaging
In Redis, use the
PUBLISH command to send a message to all clients subscribed to a specific channel. The syntax is PUBLISH channel message, where channel is the topic name and message is the text sent to subscribers.Syntax
The PUBLISH command sends a message to all subscribers of a given channel.
- channel: The name of the channel to send the message to.
- message: The text message you want to send.
Redis delivers the message to all clients subscribed to that channel.
redis
PUBLISH channel message
Example
This example shows how to publish a message to a channel named news. Subscribers to news will receive the message.
redis
127.0.0.1:6379> PUBLISH news "Hello subscribers!" (integer) 1
Output
(integer) 1
Common Pitfalls
Common mistakes when using PUBLISH include:
- Publishing to a channel with no subscribers returns 0 and no message is delivered.
- Using incorrect channel names or typos causes messages to go unnoticed.
- Expecting
PUBLISHto store messages permanently; it only sends messages live to current subscribers.
Always ensure subscribers are connected before publishing.
redis
127.0.0.1:6379> PUBLISH wrongchannel "Test" (integer) 0 # Correct usage with subscribers connected: 127.0.0.1:6379> PUBLISH news "Update available" (integer) 2
Output
(integer) 0
(integer) 2
Quick Reference
| Command | Description | Returns |
|---|---|---|
| PUBLISH channel message | Sends message to all subscribers of channel | Number of clients that received the message |
| SUBSCRIBE channel | Subscribe to receive messages from channel | Messages sent to channel |
| UNSUBSCRIBE channel | Stop receiving messages from channel | Confirmation of unsubscription |
Key Takeaways
Use PUBLISH to send messages to all clients subscribed to a channel.
The command returns the number of clients that received the message.
Messages are only delivered to currently connected subscribers.
Ensure subscribers are connected before publishing to avoid lost messages.
Channel names must match exactly for subscribers to receive messages.