如何为 aiocache 添加 redis 哨兵模式?

解读

国内互联网公司在高并发场景下普遍采用 Redis Sentinel(哨兵)做高可用,FastAPI 服务若用 aiocache 做异步缓存,就必须让 aiocache 识别哨兵地址并完成主节点自动切换。面试时,面试官想确认两点:

  1. 你是否真的在生产环境连过哨兵,而不是只连过单机 Redis;
  2. 你是否理解 aiocache 的插件化设计,能用“自定义后端”优雅地解决问题,而不是硬改源码。

因此,回答要给出“可落地的配置代码 + 故障切换验证思路”,并指出常见踩坑(如 aioredis 版本、只读路由、超时参数)。

知识点

  1. aiocache 的 Backend 抽象:SimpleMemoryBackend、RedisBackend、MemcachedBackend 均继承自 BaseBackend,可通过继承 BaseBackend 注入自定义连接逻辑。
  2. aioredis.sentinel.Sentinel 对象:通过 sentinel.master_for(service_name) 获取主节点连接池,slave_for 可获取只读副本。
  3. aiocache 0.12+ 开始把“连接池”作为 RedisBackend 的私有属性 _pool,因此自定义后端只需在 _build_pool 阶段返回 Sentinel 托管的连接池即可。
  4. 国内云厂商(阿里云、腾讯云、华为云)的 Redis 哨兵默认要求“db=0”且禁止 SELECT 命令,自定义后端里要禁用 db 参数。
  5. FastAPI 启动事件:@app.on_event("startup") 里创建 Cache 实例并挂载到 app.state,关闭事件里记得 await cache.close(),防止协程泄漏。

答案

  1. 安装依赖
    pip install aiocache==0.12.2 aioredis==2.0.1 # 国内镜像加 -i https://pypi.tuna.tsinghua.edu.cn/simple

  2. 自定义 SentinelBackend

from aiocache.backends.redis import RedisBackend
from aioredis.sentinel import Sentinel
from aioredis import ConnectionPool

class SentinelBackend(RedisBackend):
    def __init__(self, sentinel_nodes, service_name, **kwargs):
        # 去掉 db 参数,国内云 Redis 哨兵禁用 SELECT
        kwargs.pop("db", None)
        self.sentinel_nodes = sentinel_nodes
        self.service_name = service_name
        super().__init__(**kwargs)

    async def _build_pool(self, **kwargs):
        sentinel = Sentinel(self.sentinel_nodes, socket_timeout=0.2, encoding="utf-8")
        # 只返回主节点连接池,保证读写一致
        pool = sentinel.master_for(
            self.service_name,
            connection_pool_class=ConnectionPool,
            max_connections=50,
            retry_on_timeout=True,
            socket_keepalive=True,
        )
        return pool
  1. FastAPI 集成
from fastapi import FastAPI
from aiocache import Cache

app = FastAPI()

@app.on_event("startup")
async def startup():
    app.state.cache = Cache(
        SentinalBackend(
            sentinel_nodes=[("sentinel1.mycorp.cn", 26379),
                            ("sentinel2.mycorp.cn", 26379),
                            ("sentinel3.mycorp.cn", 26379)],
            service_name="mymaster",
            serializer="pickle"   # 支持 Python 对象
        )
    )

@app.on_event("shutdown")
async def shutdown():
    await app.state.cache.close()

@app.get("/demo")
async def demo():
    await app.state.cache.set("k", "v", ttl=60)
    return await app.state.cache.get("k")
  1. 本地验证故障切换
  • 把主节点 redis-cli DEBUG sleep 30 模拟宕机,哨兵完成 +switch-master 后,继续请求 /demo,返回 200 即表示切换成功。
  • 观察日志:aioredis 会抛出 MasterNotFoundError 一次,随后重连成功,业务无感知。

拓展思考

  1. 读写分离:若读流量巨大,可在 SentinelBackend 里再封装 slave_for 连接池,get 操作优先走 slave,set/delete 走 master;注意 slave 延迟带来的短暂脏读。
  2. 熔断降级:当 Sentinel 全部不可用时,可降级到 SimpleMemoryBackend,保证核心接口不炸;降级策略可放在自定义 Backend 的 _build_pool 异常分支里。
  3. 监控告警:通过 FastAPI 的 Starlette exporter 把 cache.hit、cache.miss、sentinel.switch_master 事件打到 Prometheus,结合 Grafana 配置“主从切换次数”告警,国内夜班运维常用飞书/钉钉 webhook 通知。
  4. 版本升级:aioredis 3.x 将 sentinel 模块重构成 asyncio-redis-sentinel,需调整连接池初始化方式;面试时可主动提及“我会锁定 aioredis 2.x 版本,等 aiocache 官方适配后再升级”,体现稳定性优先的思维。