近期写爬虫,需要与php进行交互,那我就直接让php往redis丢队列。
然后我从里面拿。
监听就直接使用redis了。
我py这台服务器,反正就一直开着两个频道。
php如果有更新请求,那我就直接频道有任务。
完成后,通过频道发消息回去。让php再去监听,然后发起提示框。
发布/订阅
redis-py包含一个PubSub对象,该对象订阅频道并侦听新消息。创建PubSub对象很容易。
>>> r = redis.StrictRedis(...)>>> p = r.pubsub()
创建PubSub实例后,即可订阅通道和模式。
>>> p.subscribe('my-first-channel', 'my-second-channel', ...)>>> p.psubscribe('my-*', ...)
现在,PubSub实例已订阅了这些通道/模式。订阅确认可以通过从PubSub实例读取消息来查看。
>>> p.get_message(){'pattern': None, 'type': 'subscribe', 'channel': 'my-second-channel', 'data': 1L}
>>> p.get_message(){'pattern': None, 'type': 'subscribe', 'channel': 'my-first-channel', 'data': 2L}
>>> p.get_message(){'pattern': None, 'type': 'psubscribe', 'channel': 'my-*', 'data': 3L}
从PubSub实例读取的每个消息都将是具有以下键的字典。
现在发送一条消息。
# the publish method returns the number matching channel and pattern# subscriptions. 'my-first-channel' matches both the 'my-first-channel'
# subscription and the 'my-*' pattern subscription, so this message will
# be delivered to 2 channels/patterns>>> r.publish('my-first-channel', 'some data')
2
>>> p.get_message(){'channel': 'my-first-channel', 'data': 'some data', 'pattern': None, 'type': 'message'}
>>> p.get_message(){'channel': 'my-first-channel', 'data': 'some data', 'pattern': 'my-*', 'type': 'pmessage'}
取消订阅这里就不说了,你关闭运行就行哈哈哈
import time
#引入redis类
from store import redis
#执行到我了,首先
# 监听到sub中的数据变换 # 这个命令的循环放在外面 一秒执行一次
# 可以封装成类来调取
# 注意 频道由我这个类开启
redisPubList = redis.pubsub()
res = redisPubList.subscribe('sub_football_list','sub_basketball_list');
#监听状态:有消息发布了就拿过来
#版本 2.0
for item in redisPubList.listen(): #监听状态:有消息发布了就拿过来
if item['type'] == 'message':
print(item['channel'])
print(item['data'])
# 死循环监听 版本1.0
# while (redisPubList):
# # 慢一点
# time.sleep(3)
# # 开启两个频道
# # 如果得到的信息是none 就不做处理继续循环
# msg = redisPubList.get_message()
# if msg != None:
# # 得到的是dict类型 进行字符串切割
# #{'type': 'message', 'pattern': None, 'channel': b'sub_football_list', 'data': b'6666'}
# print(msg['data'])
# print(msg)
print('duangduangduangduang')
exit()
# 加上decode_responses=True即可解决
redis_store = redis.StrictRedis(host='127.0.0.1', port=6379, decode_responses=True).