python - 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)。这意味着不可能摆脱缓存的值。只有在手动删除密钥后,我才能获得新的值。
解决方案
推荐阅读
- javascript - 如何在 chrome 中调试 Web 应用程序?
- python - 如何静默或重定向 shutil.move() 的输出或以静默模式移动文件的其他方法?
- php - PHP $_POST 数组形式的内容
- mysql - MySQL:限制结果集中每个玩家返回的记录数
- mysql - 如何按州计算订单
- c - C 中的编译器错误,错误:预期表达式
- python - 数组中的 Numpy“放置对象”
- python - 将 Python 输出打印到 HTML 中的特定 div
- python - 带有 selenium python 的谷歌表单中的单选按钮
- c++ - 在实现细节中“使用命名空间”的便捷方式(仅标头库)?