python操作redis进行发布和订阅消息

本文介绍了如何在远程服务器上安装并启动Redis,然后展示Python代码分别用于实现订阅和发布消息的功能。通过这种方式,可以利用Redis进行实时数据传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在远程服务器安装redis,并启动
订阅端代码

import redis
pool=redis.ConnectionPool(host='192.168.100.30',
                          port=6379,db=0,
                          password='123456')
r=redis.StrictRedis(connection_pool=pool)
p=r.pubsub()
p.subscribe("spub","cctv1")
for item in p.listen():
    print("Listen on channel : %s "%item['channel'].decode())
    if item['type']=='message':
        data=item['data'].decode()
        print("From %s get message : %s"%(item['channel'].decode(),item['data'].decode()))
        if item['data']=='over':
            print(item['channel'].decode(),'停止发布')
            break
p.unsubscribe('spub')
print("取消订阅")

发布端
Python Redis 的结合可以非常高效地实现实时通信功能,特别是通过Redis发布/订阅(Pub/Sub)机制。以下是关于如何利用 Python 结合 Redis 进行消息发布的简要介绍: ### 使用步骤 #### 安装依赖库 首先需要安装 `redis-py` 库来操作 Redis 数据库: ```bash pip install redis ``` #### 发布者示例代码 创建一个简单的脚本作为消息发送方,即“发布者”。它会向指定频道推送信息。 ```python import redis # 创建连接到本地运行的Redis服务器实例,默认端口6379 r = redis.Redis(host='localhost', port=6379) def publish_message(channel, message): r.publish(channel, message) print(f"Published '{message}' to channel {channel}") if __name__ == "__main__": # 测试用的消息通道名内容 test_channel = "test-channel" test_message = "Hello from Publisher!" publish_message(test_channel, test_message) ``` #### 订阅者示例代码 同时还需要另一个进程监听某个特定的主题或所有主题,并处理收到的信息,这就是所谓的 “订阅者”。 ```python import redis import time class Subscriber: def __init__(self, channels=[]): self.redis_client = redis.Redis() self.pubsub = self.redis_client.pubsub() # 开启一个pub/sub模式客户端 if isinstance(channels, list) and len(channels)>0: for ch in channels: self.subscribe_to(ch) def subscribe_to(self, channel_name): """Subscribe this client instance to the given channel.""" self.pubsub.subscribe(**{channel_name: self.message_handler}) @staticmethod def message_handler(message): if message['type'] != 'subscribe': print("Received:", message["data"].decode()) subscriber_instance = Subscriber(["test-channel"]) while True: try: message = subscriber_instance.pubsub.get_message(timeout=1.0) time.sleep(0.5) except KeyboardInterrupt: break finally: subscriber_instance.pubsub.close() print('Subscriber stopped.') ``` 在这个例子中我们定义了一个名为 `Subscriber` 的类用于管理对多个频道的订阅以及接收到数据后的响应逻辑;而主循环则不断检查是否有新的消息传入并打印出来直到程序终止为止。 以上就是基于Python语言实现基本的Redis Publish / Subscribe 功能的基本方式。这种架构非常适合构建事件驱动的应用场景或是分布式系统间的通讯需求等场合。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值