使用 @lru_cache 缓存配置时如何监听 consul 变更并失效?

解读

国内生产环境普遍把 Consul 当作“配置+服务发现”的统一中枢,FastAPI 微服务启动后会把 Consul 里的 DB 连接串、降级开关、限流阈值等热点配置读进内存,再用 @functools.lru_cache(maxsize=None) 做进程级缓存,避免每次请求都走一次网络 IO。
面试官真正想问的是:

  1. 你怎么保证“配置更新”与“缓存失效”这两个动作原子且及时;
  2. 在高并发场景下,如何让所有 worker 同步失效,又不引发缓存击穿;
  3. 如果 Consul 挂了,缓存策略如何降级。
    一句话:既要利用 lru_cache 的极致性能,又要让 Consul 的“最终一致性”在秒级内变成“业务可见一致性”。

知识点

  1. @lru_cache 本质是把函数参数→返回结果绑死在内存 dict,没有主动过期接口,只能“清全部”或“重启进程”。
  2. Consul 提供两种监听机制:
    • Long-polling /v1/kv/<key>?index=<waitIndex>&wait=55s(阻塞查询);
    • 基于 TTL 的 Health Check + WebSocket 推送(企业版)。
      国内公有云托管 Consul 通常只开放 80/443,Long-polling 最通用。
  3. FastAPI 的同步层:
    • 单进程 Uvicorn 下,失效只要 functools.cache_clear();
    • Gunicorn + Uvicorn Worker 模型(preload_app=False)下,每个 Worker 是独立内存,需要“外部事件”广播。
  4. 失效广播方案:
    • 本地:Python 信号 signal.SIGUSR1 + 自写 cache_clear();
    • 跨进程:Redis Pub/Sub、Nacos 的 UDP 推送、Consul-template + 热更新;
    • 云原生:Sidecar 把变更写成文件,通过 inotify 触发 Python 重新加载。
  5. 并发安全:清缓存瞬间有大量请求涌入,需要用“双重检查 + 单飞锁”或“异步刷新”策略,防止缓存击穿压垮下游。
  6. 降级:Consul 不可用时,保留旧配置继续服务,同时告警;不可接受脏数据则进入“只读熔断”。

答案

给出一套可直接落地的“Long-polling + Redis 广播 + 惰性刷新”方案,代码量控制在 50 行以内,满足国内主流云原生场景。

# config.py
import functools
import os
import httpx
import aioredis
import json
import asyncio
from typing import Dict

CONSUL_ADDR = os.getenv("CONSUL_HTTP_ADDR", "http://consul.service.consul:8500")
REDIS_URL   = os.getenv("REDIS_URL", "redis://redis.service.consul:6379/0")
CONFIG_KEY  = "config/app"

# 全局 redis 客户端,单例
redis = None

async def get_redis():
    global redis
    if redis is None:
        redis = aioredis.from_url(REDIS_URL, decode_responses=True)
    return redis

# 真正去 Consul 拿配置
async def _fetch_from_consul() -> Dict:
    async with httpx.AsyncClient(base_url=CONSUL_ADDR, timeout=60) as cli:
        # 阻塞 55s,index=0 表示首次
        resp = await cli.get(f"/v1/kv/{CONFIG_KEY}", params={"raw": "true"})
        resp.raise_for_status()
        return resp.json()

# 带 lru_cache 的读配置入口
@functools.lru_cache(maxsize=None)
def get_config() -> Dict:
    # 注意:lru_cache 只能缓存同步函数,这里用 asyncio.run 把异步桥接
    return asyncio.run(_fetch_from_consul())

# 清缓存,供外部调用
def purge_config_cache():
    get_config.cache_clear()

# 监听协程,跑在后台
async def watch_consul():
    consul_index = "0"
    while True:
        try:
            async with httpx.AsyncClient(base_url=CONSUL_ADDR, timeout=60) as cli:
                resp = await cli.get(f"/v1/kv/{CONFIG_KEY}",
                                     params={"index": consul_index, "wait": "55s", "raw": "true"})
                if resp.status_code == 200:
                    # 拿到新 index,说明数据变更
                    consul_index = resp.headers.get("X-Consul-Index", consul_index)
                    # 推送到 Redis 频道,让所有 Worker 失效
                    r = await get_redis()
                    await r.publish("config:changed", "1")
        except Exception as e:
            # 网络抖动,指数退避
            await asyncio.sleep(5)

# Redis 订阅协程,收到消息后清本地缓存
async def subscribe_redis():
    r = await get_redis()
    ch = (await r.subscribe("config:changed"))[0]
    async for _ in ch:
        purge_config_cache()

启动方式(单进程调试):

# main.py
from fastapi import FastAPI
from config import get_config, watch_consul, subscribe_redis
import asyncio

app = FastAPI()

@app.get("/demo")
async def demo():
    cfg = get_config()
    return {"mysql_host": cfg["mysql"]["host"]}

@app.on_event("startup")
async def startup():
    # 起两个后台协程:一个监听 Consul,一个订阅 Redis
    asyncio.create_task(watch_consul())
    asyncio.create_task(subscribe_redis())

生产部署(Gunicorn + Uvicorn):

gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --preload

关键点解释

  1. get_config() 用 lru_cache 做进程级缓存,调用零成本。
  2. 每个 Worker 独立运行 watch_consul 与 subscribe_redis,Consul 变更只需一次 Long-polling 返回,Redis 广播保证所有 Worker 同时 cache_clear()。
  3. 清缓存瞬间,下一个请求会触发 get_config() 未命中,自动回源 Consul 并重新填充缓存,实现“懒加载”。
  4. 如果 Consul 挂掉,watch_consul 会退避重试,本地缓存继续服务;若业务不允许脏数据,可在 _fetch_from_consul 里抛异常,让上游熔断。
  5. 整个方案无外部依赖锁,Redis 只当消息总线,即使 Redis 挂了,最多退化为“各 Worker 自己 Long-polling”,可用性仍然满足国内 SLA 要求。

拓展思考

  1. 配置分层:把“热配置”(限流阈值)放 Consul,把“冷配置”(业务文案)放 Nacos/Apollo,如何在一个 @lru_cache 里做多源聚合?
  2. 灰度发布:Consul Key 带版本号 config/app/v2,如何在 FastAPI 里按用户维度做“缓存多版本共存”,避免全局失效?
  3. 大规模集群:Redis 广播成为瓶颈,可改用 Kafka/ONS 消息队列,或者 Consul-Agent 本地 exec 触发脚本,直接给容器发 SIGUSR1,实现零中间件依赖。
  4. 性能极限:@lru_cache 是线程级锁,高并发下能否用 cachetools.TTLCache + asyncio.Lock 做异步可过期缓存,彻底摆脱“手动失效”?
  5. 安全合规:金融场景要求“配置不落磁盘”,如何把 Consul 的 KV 加密选项与 Python 的 cryptography 库结合,保证缓存明文只在内存?