Laravel 後臺與爬蟲互動-通過 Redis 的頻道訂閱來通訊

kuibatian發表於2019-11-04

近期寫爬蟲,需要與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'}

取消訂閱這裡就不說了,你關閉執行就行哈哈哈

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檔案

Laravel 後臺與爬蟲互動-通過 Redis 的頻道訂閱來通訊

redis 開啟客戶端傳送一條訊息給我其中一個頻道

Laravel 後臺與爬蟲互動-通過 Redis 的頻道訂閱來通訊

py列印出訊息

Laravel 後臺與爬蟲互動-通過 Redis 的頻道訂閱來通訊

解釋一下 控制檯列印帶了一個b和單引號

# 加上decode_responses=True即可解決
redis_store = redis.StrictRedis(host='127.0.0.1', port=6379, decode_responses=True).

大功告成,2333.請素質三連擊喲!

相關文章