使用redis pub/sub 实现消息发布

import redis
import time

r=redis.StrictRedis(host="127.0.0.1",port=6379)
#你也可以选择使用地址池的方式建立连接

while True:
  if __name__='__main__':
    dis=Get_Distance()
    p=r.publish()
    p.subscribe("first channel") #订阅

    r.publish("first channel",dis) #发布(调用了Get_Distance 函数)
    p.get_message()
    time.sleep(0.5) #在网络状态不佳时,若挂起时间太短则返回值为None
    a=p.get_message()
    print a     

此处我把 publish 同 subscribe 放在同一个函数中运行。

测试结果:

 

此外,这只是可以读出订阅后收到的消息。程序若要对消息进行处理,则需要使用回调函数。

 

运行环境:

python-2.7

Ubuntu-16.4

posted @ 2017-08-09 11:37  sfdswy  阅读(356)  评论(0)    收藏  举报