https://cloud.tencent.com/developer/article/1347437 python中的Redis鍵空間通知(過期回調)
set notify-keyspace-events KEA 【KEA參照以下字符進行設置】
此有缺點:最大的缺點是Pub / Sub實現要求發布者和訂閱者一直處於啟動狀態。訂閱服務器在停止或連接丟失時會丟失數據。
【意思:就是如果服務端在意外情況下出現重啟或斷開,需要重新設置(windows)】
字符 | 發送通知 |
---|---|
K | 鍵空間通知,所有通知以 keyspace@ 為前綴,針對Key |
E | 鍵事件通知,所有通知以 keyevent@ 為前綴,針對event |
g | DEL 、 EXPIRE 、 RENAME 等類型無關的通用命令的通知 |
$ | 字符串命令的通知 |
l | 列表命令的通知 |
s | 集合命令的通知 |
h | 哈希命令的通知 |
z | 有序集合命令的通知 |
x | 過期事件:每當有過期鍵被刪除時發送 |
e | 驅逐(evict)事件:每當有鍵因為 maxmemory 政策而被刪除時發送 |
A | 參數 g$lshzxe 的別名,相當於是All |

import time from redis import StrictRedis redis = StrictRedis(host='localhost', port=6379) pubsub = redis.pubsub() def event_handler(msg): print(msg) data = msg['channel'].decode().split(':')[1] print('***',data, redis.get(data)) pubsub.psubscribe(**{'__keyspace@0__:*': event_handler}) print('Starting message loop') while True: message = pubsub.get_message() if message: print(message) else: time.sleep(0.01)

import time from redis import StrictRedis redis = StrictRedis(host='localhost', port=6379) pubsub = redis.pubsub() pubsub.psubscribe('__keyspace@0__:*') print('Starting message loop') while True: message = pubsub.get_message() if message: print(message) else: time.sleep(0.01)

# python 3.7 import redis pool = redis.ConnectionPool(host='localhost', port=6379) r = redis.Redis(connection_pool=pool) r.execute_command('config set notify-keyspace-events KEA') # 發布端,判斷如果是第一次就執行 r.setex('a2',2,'a1')

import redis,json,time r = redis.ConnectionPool(host='127.0.0.1',port=6379) rw = redis.Redis(connection_pool=r) for i in range(1,10): rw.zadd('cookie_pool',json.dumps({'a1':1,'a2':2}),int(time.time())) time.sleep(1) print('設置 1個') def alive(time_space=10 * 3): ''' :param time: 每隔10分鍾檢測一下 :return: ''' # 對應 _self.rw.zadd('cookie_pool', json.dumps(d), int(time.time())) while True: # 拿到前面的1個,並loads _ = rw.zrange('cookie_pool', 0, 0)[0] # 拿到分值 score = rw.zscore('cookie_pool', _) print(score,time.time()-score) # 如果分值大於10分鍾,就開始進行驗證cook保活 if time.time() - score >= time_space: # 進行刪除 rw.zrem('cookie_pool', _) # 轉義第一個集合的值 first_set = json.loads(_.decode()) # 此處調用cook保活驗證,,返回 bool,,假設為True cook_alive = True if cook_alive: print('正在設置',first_set) rw.zadd('cookie_pool', json.dumps(first_set), int(time.time())) else: print('已自動刪除') # 什么都不做,自動扔掉 else: print('檢測時間未到') time.sleep(1) alive()