Redis发布-订阅模式之Channel的发布订阅
import redis
# 连接到Redis服务器
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
# 发布消息到channel
def publish_message(channel, message):
redis_client.publish(channel, message)
# 订阅特定channel的消息
def subscribe_to_channel(channel):
pubsub = redis_client.pubsub()
pubsub.subscribe(channel)
for message in pubsub.listen():
if message['type'] == 'message':
print(f"Received message: {message['data'].decode()}")
# 示例使用
channel_name = "my_channel"
message_to_publish = "Hello, Redis!"
# 发布消息
publish_message(channel_name, message_to_publish)
# 订阅消息
subscribe_to_channel(channel_name)
这段代码演示了如何使用redis-py
库在Redis中发布和订阅消息。首先,我们连接到Redis服务器。然后,我们定义了publish_message
函数来发布消息到指定的channel,以及subscribe_to_channel
函数来订阅一个channel并打印接收到的消息。最后,我们使用示例展示了如何调用这些函数来发送和接收消息。
评论已关闭