Middle
How is message exchange implemented via broker in Redis?
sobes.tech AI
Answer from AI
In Redis, the messaging system is implemented through the Pub/Sub (publish/subscribe) mechanism. This allows clients to subscribe to channels and receive messages published by other clients.
Main features:
- Clients subscribe to one or more channels.
- When a message is published to a channel, Redis instantly sends it to all subscribers.
- Messages are not stored in Redis — if a client is not subscribed at the moment of publication, it will not receive the message.
Example of usage in Python with the redis-py library:
import redis
r = redis.Redis()
# Subscriber
pubsub = r.pubsub()
pubsub.subscribe('channel1')
for message in pubsub.listen():
if message['type'] == 'message':
print(f"Received message: {message['data'].decode()}")
# From another client
r.publish('channel1', 'Hello, world!')
Thus, Redis acts as a simple and fast message broker without complex queues and delivery guarantees.