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