feat(postgresql): 增强PostgreSQL会话级性能优化配置
This commit is contained in:
@@ -218,29 +218,47 @@ async def _enable_sqlite_optimizations(engine: AsyncEngine):
|
||||
logger.warning(f"⚠️ SQLite性能优化失败: {e},将使用默认配置")
|
||||
|
||||
|
||||
async def _enable_postgresql_optimizations(engine: AsyncEngine):
|
||||
"""启用PostgreSQL性能优化
|
||||
async def _enable_postgresql_optimizations(engine: AsyncEngine) -> None:
|
||||
"""启用 PostgreSQL 会话级性能优化。
|
||||
|
||||
优化项:
|
||||
- 设置合适的 work_mem
|
||||
- 启用 JIT 编译(如果可用)
|
||||
- 设置合适的 statement_timeout
|
||||
|
||||
Args:
|
||||
engine: SQLAlchemy异步引擎
|
||||
包含:
|
||||
- work_mem:单次排序/哈希可用内存
|
||||
- statement_timeout:单条语句超时
|
||||
- synchronous_commit:提交同步级别
|
||||
- jit:是否启用 JIT
|
||||
- idle_in_transaction_session_timeout:事务空闲超时
|
||||
- lock_timeout:等待锁超时
|
||||
"""
|
||||
try:
|
||||
async with engine.begin() as conn:
|
||||
# 设置会话级别的参数
|
||||
# work_mem: 排序和哈希操作的内存(64MB)
|
||||
# 排序/哈希内存,注意这是“每个排序操作”的上限,不要乱调太大
|
||||
await conn.execute(text("SET work_mem = '64MB'"))
|
||||
# 设置语句超时(5分钟)
|
||||
await conn.execute(text("SET statement_timeout = '300000'"))
|
||||
# 启用自动 EXPLAIN(可选,用于调试)
|
||||
# await conn.execute(text("SET auto_explain.log_min_duration = '1000'"))
|
||||
|
||||
# 单条语句超时(1 分钟)
|
||||
await conn.execute(text("SET statement_timeout = '60000'"))
|
||||
|
||||
# 提交同步级别:'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:
|
||||
logger.warning(f"⚠️ PostgreSQL性能优化失败: {e},将使用默认配置")
|
||||
logger.warning(
|
||||
f"⚠️ PostgreSQL 会话级性能优化失败: {e},将使用默认配置"
|
||||
)
|
||||
|
||||
|
||||
async def get_engine_info() -> dict:
|
||||
|
||||
Reference in New Issue
Block a user