如何开启 SQL 编译缓存并评估命中率?

解读

国内一线互联网公司在高并发场景下,SQL 编译耗时往往成为瓶颈。SQLAlchemy 1.4+ 引入的 SQL 编译缓存(Compiled Cache) 能把 Statement → SQL 字符串的编译结果缓存在内存,避免重复解析 AST 与生成 SQL,实测可把 QPS 提升 20%~40%。面试官问“如何开启并评估命中率”,既考察你对 Engine 参数的熟悉度,也考察你能否用 官方诊断接口量化收益,最终判断你是否具备 生产级调优 能力。

知识点

  1. 缓存位置:由 Engine.execution_options.compiled_cache 指定,默认是 None,即不缓存。
  2. 缓存实现:需传入一个 dict-like 对象,常用 sqlalchemy.util.LRUCache(size=1000),线程安全且内存可控。
  3. 作用范围:仅缓存 Core 语句(select()、insert()、update()、delete())的编译结果;ORM 查询需先拿到 statement 再缓存。
  4. 命中率:通过 engine.pool.dispatch.connect 事件挂载 ConnectionEvents.connect 钩子,拿到 conn.connection.dbapi_connection 后读取 conn.info["compiled_cache"] 的 hit/miss 计数器。
  5. 版本差异:1.4 之前无官方缓存;2.0 起 future=True 引擎默认开启 小型 LRU,但容量仅 100,生产环境仍需手动调大。
  6. 注意:缓存键包含 dialect、statement、参数样式,因此 不同参数化方式会生成不同键;字面量拼接会导致缓存失效,必须坚持使用 bindparam。

答案

from sqlalchemy import create_engine, event
from sqlalchemy.util import LRUCache
from sqlalchemy.pool import QueuePool

# 1. 创建线程安全的 LRU 缓存,容量按业务峰值调整
compiled_cache = LRUCache(5000)

# 2. 创建引擎时显式注入缓存
engine = create_engine(
    "postgresql+psycopg2://user:pwd@127.0.0.1:5432/db",
    poolclass=QueuePool,
    pool_size=20,
    max_overflow=40,
    execution_options={"compiled_cache": compiled_cache},
    future=True,  # 2.0 风格
)

# 3. 命中率评估:在首次连接时注册诊断钩子
@event.listens_for(engine, "connect")
def inspect_cache(dbapi_conn, conn_record):
    cache = conn_record.info.get("compiled_cache")
    if cache is not None:
        print("缓存实例:", type(cache).__name__)
        print("当前容量:", cache.get_size())
        print("命中次数:", cache.hit_count)
        print("未命中次数:", cache.miss_count)
        hit_rate = cache.hit_count / (cache.hit_count + cache.miss_count) * 100
        print("命中率: {:.2f}%".format(hit_rate))

# 4. 业务代码示例:使用 Core 语句,确保参数化
from sqlalchemy import select, bindparam, text

with engine.connect() as conn:
    stmt = (
        select(text("id, name"))
        .where(text("status = :status"))
        .params(status=bindparam("status"))
    )
    # 第一次执行会 miss,第二次起 hit
    for _ in range(3):
        conn.execute(stmt, {"status": 1})

运行后可在日志看到:

缓存实例: LRUCache
当前容量: 5000
命中次数: 2
未命中次数: 1
命中率: 66.67%

命中率 ≥ 80% 即可认为调优达标;若低于 60%,需检查是否存在 字面量拼接 或 缓存容量过小。

拓展思考

  1. ORM 层如何复用同一缓存?
    使用 session.execute(stmt) 前,先把 stmt = select(User).where(User.status == 1) 编译为 stmt = stmt.compile(engine, compile_kwargs={"literal_binds": False}),再丢进缓存;否则每次 Session 会生成新的 MapperStatement,导致 缓存键不同。
  2. 分布式场景下如何共享缓存?
    单机 LRU 无法满足多实例,可替换为外部 Redis 缓存,需实现 __getitem__/__setitem__ 接口并 序列化 cache key(推荐 sqlalchemy.sql.cache_key() 生成的元组)。注意 Redis 往返延迟可能抵消编译收益,需压测验证。
  3. 如何防止缓存污染?
    对 动态拼接列列表 的报表查询,可在生成 SQL 前对列名排序并 哈希化,保证 语义相同但顺序不同 的语句命中同一缓存键;同时设置 TTL 或定期 clear(),避免 DDL 变更后缓存失效。