Laravel 后台与爬虫交互-通过 Redis 的频道订阅来通信
python中使用redis开启监听频道
前言
近期写爬虫,需要与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实例读取的每个消息都将是具有以下键的字典。
- 类型:以下之一:'subscribe','unsubscribe','psubscribe','punsubscribe','message','pmessage'
- 频道:[取消]订阅的频道或消息发布到的频道
- 模式:与已发布消息的频道匹配的模式。除“ pmessage”类型外,在所有情况下均将为“无”。
- data:消息数据。对于[un] subscribe消息,此值将是该连接当前订阅的通道和模式的数量。对于[p]条消息,此值将是实际发布的消息。
现在发送一条消息。
# 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'}
取消订阅这里就不说了,你关闭运行就行哈哈哈
我的代码 1。 监听队列死循环版本与 2 listen版本
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()
运行测试
执行我的py文件
redis 打开客户端发送一条消息给我其中一个频道
py打印出消息
解释一下 控制台打印带了一个b和单引号
# 加上decode_responses=True即可解决
redis_store = redis.StrictRedis(host='127.0.0.1', port=6379, decode_responses=True).
大功告成,2333.请素质三连击哟!
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: