Redis 消息订阅
In [2]: p = cache.pubsub() In [3]: p Out[3]: <redis.client.PubSub at 0x10fecb748> In [5]: def echo_message(message): ...: print("===========") ...: print(message, type(message)) ...: print("===========") ...: In [6]: p.subscribe(ywhyme_test=echo_message) In [7]: cache.publish("ywhyme_test","hello world") Out[7]: 1 In [8]: cache.publish("ywhyme_test","hello world") Out[8]: 1 # 订阅时发送的 message In [9]: p.get_message() Out[9]: {'type': 'subscribe', 'pattern': None, 'channel': b'ywhyme_test', 'data': 1} In [10]: p.get_message() =========== {'type': 'message', 'pattern': None, 'channel': b'ywhyme_test', 'data': b'hello world'} <class 'dict'> =========== In [11]: p.get_message() =========== {'type': 'message', 'pattern': None, 'channel': b'ywhyme_test', 'data': b'hello world'} <class 'dict'> =========== In [12]: p.get_message() In [17]: cache.publish("ywhyme_test","hello world") ...: Out[17]: 1 In [18]: p.get_message() =========== {'type': 'message', 'pattern': None, 'channel': b'ywhyme_test', 'data': b'hello world'} <class 'dict'> =========== In [19]: p.get_message() # 设置一个子线程用于处理 get message In [21]: p.run_in_thread(sleep_time=0.001) Out[21]: <PubSubWorkerThread(Thread-4089, started 123145592598528)> In [22]: p.get_message() In [23]: cache.publish("ywhyme_test","hello world") ...: Out[23]: =========== 1 {'type': 'message', 'pattern': None, 'channel': b'ywhyme_test', 'data': b'hello world'} <class 'dict'> =========== In [24]: cache.publish("ywhyme_test","hello world") ...: Out[24]: =========== 1 {'type': 'message', 'pattern': None, 'channel': b'ywhyme_test', 'data': b'hello world'} <class 'dict'> ===========
参考 : https://github.com/andymccurdy/redis-py
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步