- 发布者
import redis
pool = redis.ConnectionPool(host="xxxxx", port=6382, db=0, password="xxxxx")
r = redis.Redis(connection_pool=pool)
r.publish("my-first-channel", "first:哈哈哈")
r.publish("my-second-channel", "second:嘿嘿嘿")
r.publish("my-third-channel", "third:呵呵呵")
- 两个订阅者(两个线程)
import redis
from threading import Thread, current_thread
pool = redis.ConnectionPool(host="xxxxxx", port=6382, db=0, password="xxxxx")
r = redis.Redis(connection_pool=pool)
class PubSub(object):
def __init__(self):
self.pub = r.pubsub()
def subscribe(self, *args):
self.pub.subscribe(*args)
self.pub.parse_response()
self.pub.parse_response()
return self.pub
def subscribe(p):
while True:
msg = p.parse_response()
for i in msg:
print(current_thread().name, i.decode(encoding="utf8"))
if __name__ == '__main__':
t1 = Thread(target=subscribe, args=(PubSub().subscribe("my-first-channel", "my-second-channel"),))
t1.start()
t2 = Thread(target=subscribe, args=(PubSub().subscribe("my-first-channel", "my-third-channel"),))
t2.start()
t1.join()
t2.join()
官方文档-发布订阅
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)