首页 > 解决方案 > Redis 密钥过期后更新 ttl

问题描述

我在 docker 容器(redis:6.2.5)中使用 Redis 作为 Python 项目的键值存储。

我有一堂课:

class MyRedisCache:
    def __init__(self):
        self.r = redis.Redis(host="redis", db=3)

    def set_to_cache(self, key: str, value: Dict[str, Any], timeout: int = 3600):
        self.r.setex(name=key, value=value, time=timeout)

    def get_from_cache(self, key: str):
        return self.r.get(name=key)
        

我通过以下方式使用缓存类:

def get_value(key):
    value = MyRedisCache().get_from_cache(key=key)
    if value:
        logger.info(f"Got key={key} from cache with ttl={MyRedisCache().r.ttl(key)}")
    else:
        # get value from original source
        logger.info(f"Got key={key} from original source")
    return value

当我第一次尝试代码时,它运行良好。我从原始来源获取值,然后从缓存中获取值。默认缓存 ttl 为一小时。然后我意识到,即使在 1 小时后,我也会不断获得缓存值。我添加了日志,结果发现缓存在过期后只是恢复了它的 ttl。以下日志指向上一条语句。

Sep 20 10:02:12 airflow webserver[3520]: [2021-09-20 10:02:12,595] INFO Got key=test from cache with ttl=20
Sep 20 10:02:40 airflow webserver[3520]: [2021-09-20 10:02:40,276] INFO Got key=test from cache with ttl=3592

此外,当我在任何时候重新启动 redis 容器时,我的日志说 ttl 总是接近一小时(例如 3580)。这意味着不可能摆脱缓存的值。只有在手动删除密钥后,我才能获得新的值。

标签: pythonredis

解决方案


推荐阅读