feat(postgresql): 增强PostgreSQL会话级性能优化配置

This commit is contained in:
Windpicker-owo
2025-12-08 18:08:37 +08:00
parent e148cfd16b
commit 7c2843de64

View File

@@ -218,29 +218,47 @@ async def _enable_sqlite_optimizations(engine: AsyncEngine):
logger.warning(f"⚠️ SQLite性能优化失败: {e},将使用默认配置") logger.warning(f"⚠️ SQLite性能优化失败: {e},将使用默认配置")
async def _enable_postgresql_optimizations(engine: AsyncEngine): async def _enable_postgresql_optimizations(engine: AsyncEngine) -> None:
"""启用PostgreSQL性能优化 """启用 PostgreSQL 会话级性能优化
优化项 包含
- 设置合适的 work_mem - work_mem:单次排序/哈希可用内存
- 启用 JIT 编译(如果可用) - statement_timeout单条语句超时
- 设置合适的 statement_timeout - synchronous_commit提交同步级别
- jit是否启用 JIT
Args: - idle_in_transaction_session_timeout事务空闲超时
engine: SQLAlchemy异步引擎 - lock_timeout等待锁超时
""" """
try: try:
async with engine.begin() as conn: async with engine.begin() as conn:
# 设置会话级别的参数 # 排序/哈希内存,注意这是“每个排序操作”的上限,不要乱调太大
# work_mem: 排序和哈希操作的内存64MB
await conn.execute(text("SET work_mem = '64MB'")) await conn.execute(text("SET work_mem = '64MB'"))
# 设置语句超时5分钟
await conn.execute(text("SET statement_timeout = '300000'")) # 单条语句超时1 分钟)
# 启用自动 EXPLAIN可选用于调试 await conn.execute(text("SET statement_timeout = '60000'"))
# await conn.execute(text("SET auto_explain.log_min_duration = '1000'"))
# 提交同步级别:'local' 性能好一些,崩溃时可能丢几 ms 的数据
await conn.execute(text("SET synchronous_commit = 'local'"))
# 对大量短小查询,通常关掉 JIT 更省 CPU
await conn.execute(text("SET jit = 'off'"))
# 事务空闲超时,避免长时间占用锁
await conn.execute(
text("SET idle_in_transaction_session_timeout = '60000'")
)
# 等锁超过 5s 就报错,避免全部堆死
await conn.execute(text("SET lock_timeout = '5000'"))
# 可选:根据你预估的缓存情况设置
# await conn.execute(text("SET random_page_cost = 1.1"))
# await conn.execute(text("SET effective_cache_size = '2GB'"))
except Exception as e: except Exception as e:
logger.warning(f"⚠️ PostgreSQL性能优化失败: {e},将使用默认配置") logger.warning(
f"⚠️ PostgreSQL 会话级性能优化失败: {e},将使用默认配置"
)
async def get_engine_info() -> dict: async def get_engine_info() -> dict: