How to redis pub-sub

Here is an example of using the Redis Pub/Sub feature in Python:

import redis

# Connect to the Redis server
r = redis.Redis(host='localhost', port=6379, db=0)

# Subscribe to a channel
p = r.pubsub()
p.subscribe('channel1')

# Publish a message to the channel
r.publish('channel1', 'hello')

# Retrieve the message from the channel
message = p.get_message()
print(message)

This example creates a connection to the Redis server, subscribes to the “channel1” channel, publishes a message to the channel, and then retrieves the message from the channel. The output of this example should be:

{'channel': b'channel1', 'data': b'hello'}

Keep in mind that the get_message() method is a blocking call, so the program will wait until a message is received on the channel before continuing. If you want to receive messages asynchronously, you can use the listen() method of the PubSub object, which will call a provided callback function for each message received on the channel.

Here is an example of using the listen() method to receive messages asynchronously:

import redis

# Connect to the Redis server
r = redis.Redis(host='localhost', port=6379, db=0)

# Subscribe to a channel
p = r.pubsub()
p.subscribe('channel1')

# Define a callback function to handle incoming messages
def on_message(message):
    print(message)

# Start listening for messages
p.listen(on_message)

# Publish a message to the channel
r.publish('channel1', 'hello')

This example will print the message received on the “channel1” channel asynchronously, without blocking the main program.