पाठ 4 / 25
PUBLISH and SUBSCRIBE
Use channels to broadcast messages and understand the delivery semantics.
Live broadcast on named channels
A client subscribes to one or more channels with SUBSCRIBE; from then on, Redis pushes every message published to those channels to that connection. PUBLISH channel message sends a message to all current subscribers and returns the number of clients that received it (in a cluster, this count covers only subscribers connected to the node that ran the command). Messages are delivered in publish order per channel to each subscriber, but there is no storage, no acknowledgement and no retry: if a subscriber is disconnected, slow to reconnect, or the server restarts, messages in that window are gone. Channel names are arbitrary strings; use a consistent naming scheme such as app:domain:event or orders.updates. Pub/Sub is completely separate from the keyspace: channels are not keys, so DEL, TTL and database numbers do not apply to them.
One publisher, many subscribers
Each message goes to every subscriber connected at that moment, and is then forgotten.
Publisher and subscriber in Python (redis-py)
The subscriber's loop blocks and handles each message as it arrives.
import json, redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
# publisher
receivers = r.publish("orders.updates", json.dumps({"orderId": "o-1001", "status": "shipped"}))
print("delivered to", receivers, "subscribers")
# subscriber (usually a separate process)
pubsub = r.pubsub(ignore_subscribe_messages=True)
pubsub.subscribe("orders.updates")
for message in pubsub.listen():
event = json.loads(message["data"])
print("order", event["orderId"], "is now", event["status"])PUBLISH returning 0 is information
A return value of 0 means nobody was listening and the message vanished. Log or count it if you expected subscribers; it often reveals a typo in a channel name.
त्वरित जाँच: What does the PUBLISH command return?
- The message ID
- The channel length
- The number of clients that received the message
- Always OK
Answer
The number of clients that received the message — PUBLISH returns how many subscribers the message was delivered to.