示例如下:
import redis
import time
def event_handler(msg):
'''
监听到任何key过期后,得到的消息如下
msg ={'type': 'pmessage', #返回值类型
'pattern': '__keyevent@2__:expired', #来源
'channel': '__keyevent@2__:expired', # 实际的Channel
'data': 'mykey' # key名称
}
可以根据您要监控的key进行业务判断或触发其他事件
if msg['data']=='mykey':
do....
elif msg['data']=='yourkey':
do ----
'''
print(msg)
redis_conn = redis.Redis(host='host', port='6379', db=2, password='test.123.com', decode_responses=True)
#设置过期时间2秒
redis_conn.set('mykey', 'asjdhkjashdkjahdskjahsd', ex=2)
# 订阅消息
pubsub =redis_conn.pubsub()
# 订阅key过期事件
# __keyevent@2__:expired : __keyevent@{db}__:事件
pubsub.psubscribe(**{'__keyevent@2__:expired': event_handler})
while True:
message = pubsub.get_message()
if message:
# redis_conn.set('mykey', 'asjdhkjashdkjahdskjahsd', ex=10)
print('wqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwq')
else:
time.sleep(0.01)
keyevent