本文介绍如何在 python 中实现一种智能缓存机制——当缓存项过期且后端请求失败时,自动回退返回仍可用的旧数据,兼顾可靠性与响应性。核心思路是结合 `lru_cache` 与可变容器(如字典),在不破坏缓存结构的前提下动态刷新内容。
在构建 Webhook 代理、API 网关或任何依赖外部网络服务的中间层时,缓存是提升性能和降低下游压力的关键手段。但标准的 functools.lru_cache 是“非状态感知”的:它只管键值映射,不关心结果是否过期、是否有效,更无法处理网络临时中断等异常场景。若缓存失效后请求失败,用户将直接遭遇错误——这在高可用系统中是不可接受的。
为此,我们采用一种轻量却稳健的设计模式:缓存返回一个可变容器(如 dict),其中同时封装业务数据与元信息(如时间戳);每次调用先检查时效性,仅在“需更新且能更新成功”时才触发真实请求;若请求失败,则静默沿用当前缓存值。
以下是完整可运行的实现示例:
from functools import lru_cache
from time import time, sleep
from random import choice
MAXAGE = 5 # 缓存最大有效时间(秒)
def updating_cache(max_age=MAXAGE, fallback_on_error=True):
"""
装
饰器:为函数添加带过期检查与降级能力的缓存。
- 若缓存未过期,直接返回 result;
- 若已过期,尝试重新获取;成功则更新缓存并返回新值;
- 若重获取失败(如网络异常),且 fallback_on_error=True,则返回旧值(降级)。
"""
def decorator(func):
cached_func = lru_cache()(func)
def inner(*args, **kwargs):
try:
# 获取缓存的 timestamped dict(始终是同一对象引用)
timestamped_result = cached_func(*args, **kwargs)
# 检查是否过期
if time() - timestamped_result['timestamp'] < max_age:
return timestamped_result['result']
# 过期 → 尝试刷新
fresh_result = func(*args, **kwargs)
timestamped_result.update(fresh_result) # 原地更新
return timestamped_result['result']
except Exception as e:
# 请求失败时降级:返回过期但可用的旧数据
if fallback_on_error and 'result' in timestamped_result:
return timestamped_result['result']
raise e # 或记录日志后抛出
return inner
return decorator
# 使用示例:模拟不稳定网络下的远程查询
@updating_cache(max_age=3)
def fetch_user_profile(user_id):
# 此处应为 requests.get(...),但为演示加入随机失败
if choice([True, False, False]): # ~66% 概率失败
raise ConnectionError("Network timeout")
return {
'result': {'id': user_id, 'name': f'User-{user_id}', 'updated_at': time()},
'timestamp': time()
}✅ 关键设计亮点:
⚠️ 注意事项:
总结来说,这种“缓存+惰性刷新+优雅降级”的模式,既复用了 lru_cache 的高效哈希管理能力,又通过封装元数据赋予其生命周期感知力,是构建弹性微服务组件的实用范式。