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

转载于:https://www.cnblogs.com/ywhyme/p/10535823.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值