我可以在redis密钥过期之前保存值的更改吗

问题描述 投票:0回答:1

我找不到更好的解决方案。我的 Redis 中有 ID 和排名。我是否可以在Redis密钥过期之前将更改的排名保存到数据库中?我可以在提前 x 时间到期之前触发某个功能吗

python django redis hook
1个回答
0
投票

您可以使用 Redis 中的 TTL(生存时间),它告诉密钥还剩多少时间过期,并触发一个线程来保存您在数据库中的排名:

假设redis中有一个

rank
键,其值为
30
,那么:

import redis
from threading import Timer

# initializing the Redis client first
r = redis.StrictRedis(host='localhost', port=6379, db=0)

# simulate saving data to the database
def save_to_database(key, value):
    print(f"Saving key: {key}, value: {value} to database")
    # replace with actual database save logic
    # Example : db.save({"key": key, "rank": value})

# function to monitor and save data
def monitor_and_save(key):
    ttl = r.ttl(key)  # get the ttime to live (TTL) of the key
    if ttl > 30:
        # schedule the save operation to run 30 seconds before expiration
        delay = ttl - 30
        print(f"Scheduling save operation for key: {key} in {delay} seconds")
        Timer(delay, lambda: save_to_database(key, r.get(key).decode())).start()
    else:
        # if TTL is less than 30 seconds save immediately
        print(f"Key: {key} is about to expire, saving immediately")
        save_to_database(key, r.get(key).decode())

# for example 
# set a key with a 60 second expiration time
r.set("rank", 3, ex=60)

# monitor and save the key
monitor_and_save("rank")
© www.soinside.com 2019 - 2024. All rights reserved.