如何在异步环境下使用 Redis Sentinel 高可用?

解读

面试官抛出此题,表面问 Redis,实则考察候选人能否把 SQLAlchemy 异步事务体系 与 外部高可用缓存 无缝整合。国内互联网场景下,异步微服务 + 读写分离 + 故障自动切换 已成标配,Redis Sentinel 作为缓存高可用的事实标准,必须和 SQLAlchemy 1.4+ 的 AsyncSession、async engine 以及 连接池保活策略 协同工作。回答时要体现三点:异步驱动选型、Sentinel 拓扑感知、缓存与数据库事务一致性兜底方案。

知识点

  1. aioredis 2.x 已合并进 redis-py 4.x,统一使用 redis.asyncio.Redis.from_sentinel(),不再维护独立 aioredis 包。
  2. Sentinel 配置必须提供 主节点别名(master_name)与 密码、db、socket_keepalive、health_check_interval 等参数,否则 Kubernetes 或云原生环境下频繁 ConnectionResetError。
  3. SQLAlchemy 异步引擎通过 create_async_engine(..., pool_pre_ping=True, pool_recycle=600) 保证 连接池心跳,与 Redis Sentinel 的 故障切换窗口(通常 3–10 s)对齐,防止业务层拿到失效连接。
  4. 缓存穿透/雪崩 场景需加 本地协程锁(asyncio.Lock)+ 异步布隆过滤器,避免高并发下同时回源数据库。
  5. 国内大厂常用 OpenTelemetry 异步钩子 统一采集 SQLAlchemy 与 Redis 的 trace,面试时提及可加分。

答案

生产级异步集成步骤如下:

  1. 依赖锁定
    pip install "sqlalchemy[asyncio]>=2.0" "redis[hiredis]>=4.3" alembic asyncio-mysql
    
  2. 创建 Redis Sentinel 客户端
    from redis.asyncio import Redis
    from redis.asyncio.sentinel import Sentinel
    
    sentinel = Sentinel(
        sentinels=[("sentinel1.internal", 26379),
                   ("sentinel2.internal", 26379),
                   ("sentinel3.internal", 26379)],
        socket_keepalive=True,
        socket_keepalive_options={},
        health_check_interval=30,
        password="sentinel-pass",  # 国内云厂商要求
    )
    redis_master: Redis = sentinel.master_for(
        "mymaster", db=0, password="redis-pass", decode_responses=True
    )
    
  3. 创建 SQLAlchemy 异步引擎
    from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
    
    engine = create_async_engine(
        "mysql+asyncmy://user:pass@127.0.0.1:3306/app?charset=utf8mb4",
        pool_size=20,
        max_overflow=40,
        pool_pre_ping=True,          # 关键:保活
        pool_recycle=600,
        echo=False,
    )
    AsyncSessionLocal = async_sessionmaker(bind=engine, expire_on_commit=False)
    
  4. 缓存与事务一致性模板
    import asyncio
    from contextlib import asynccontextmanager
    
    class CacheAsideUnitOfWork:
        def __init__(self, redis: Redis, db_factory):
            self.redis = redis
            self.db_factory = db_factory
            self._lock = asyncio.Lock()
    
        @asynccontextmanager
        async def __call__(self, key: str, ttl: int = 300):
            async with self._lock:          # 协程级防击穿
                cached = await self.redis.get(key)
                if cached is not None:
                    yield cached
                    return
            async with self.db_factory() as session:
                async with session.begin():
                    # 执行业务 SQLAlchemy 查询
                    result = await session.execute(...)
                    data = result.scalar()
                    await self.redis.set(key, data, ex=ttl)
                    yield data
    
  5. 优雅重启与 Sentinel 切换监听
    通过 asyncio.create_task 启动后台协程,订阅 +switch-master 频道,一旦收到切主消息,主动丢弃 SQLAlchemy 连接池 (engine.dispose()),防止旧 TCP 连接复用。

拓展思考

  1. 双写一致性:国内金融场景要求 异步可靠事件,可引入 RocketMQ 事务消息 或 Binlog 异步消费,在 Redis 切换窗口内通过 幂等键 兜底。
  2. 分片与 Sentinel 共存:当缓存数据量超 64 GB 需 Redis Cluster 而非 Sentinel,此时 SQLAlchemy 端需改用 横向分库分表 + ShardingSphere-Proxy 异步驱动,面试可展示对 pyshard 或 sqlalchemy-sharding 的理解。
  3. 性能压测指标:在 4C8G 容器下,AsyncSession 池大小 20 + redis-py 连接池 50,可支撑 1.2 万 QPS、P99 延迟 18 ms;若延迟突刺,优先检查 TCP keepalive 与云厂商 SLB 空闲超时 是否匹配。