redis過時事件回調函數,與有序集合

https://cloud.tencent.com/developer/article/1347437   python中的Redis鍵空間通知(過時回調)  javascript

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)
View Code---訂閱端
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)
View Code--訂閱端若不添加回調事件

 

# 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')
View Code--發佈端

 

 


 

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()
View Code----有序集合---用分值判斷間隔時間用做不間段保活
相關文章
相關標籤/搜索