From ef57e51ef053027cfadbe8c92cb40dcecfcbdfb0 Mon Sep 17 00:00:00 2001 From: Pine Date: Thu, 10 Sep 2026 22:52:19 +0800 Subject: [PATCH] =?UTF-8?q?refactor(db):=20=E7=BB=9F=E4=B8=80=E5=BC=95?= =?UTF-8?q?=E6=93=8E=E4=B8=BA=E8=BF=9B=E7=A8=8B=E7=BA=A7=E5=8D=95=E4=BE=8B?= =?UTF-8?q?=EF=BC=8C=E5=90=8C=E4=B8=80=20URL=20=E5=8F=AA=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E6=B1=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 此前同一 DATABASE_URL 存在 3 个独立 engine(db 主 engine、 repositories._shared_engine、park._ASYNC_ENGINE),各自 20+20 池, 理论连接上限 120,池间不互济,仍有满载风险。 - _shared_engine:URL==config.DATABASE_URL 时直接复用 db 模块级 engine - park/tenants._get_session:同样复用主 engine - 收敛后同一 URL 进程内仅一个池(上限 40),连接数可控、池可互济 --- app/infrastructure/repositories.py | 5 +++++ app/park/tenants.py | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/app/infrastructure/repositories.py b/app/infrastructure/repositories.py index 8e91897..dfd6be8 100644 --- a/app/infrastructure/repositories.py +++ b/app/infrastructure/repositories.py @@ -3353,6 +3353,11 @@ _SHARED_ENGINES: dict[str, "object"] = {} def _shared_engine(url: str): + # 统一引擎:主库 URL 直接复用 db 模块级单例 engine(同一进程同一 URL 只有一个 + # 连接池,避免多 engine 多池叠加导致连接数倍增 / 池不互济再满载)。 + if url == config.DATABASE_URL: + from .db import engine as _main_engine + return _main_engine eng = _SHARED_ENGINES.get(url) if eng is None: from .db import make_async_engine diff --git a/app/park/tenants.py b/app/park/tenants.py index 22b96b7..fd812ec 100644 --- a/app/park/tenants.py +++ b/app/park/tenants.py @@ -41,7 +41,9 @@ _ASYNC_ENGINE = None def _get_session() -> AsyncSession: global _ASYNC_ENGINE if _ASYNC_ENGINE is None: - _ASYNC_ENGINE = make_async_engine(DATABASE_URL) + # 统一引擎:复用 db 模块级单例 engine(同一 URL 同一池,不另开池) + from ..infrastructure.db import engine as _main_engine + _ASYNC_ENGINE = _main_engine return async_sessionmaker(bind=_ASYNC_ENGINE, expire_on_commit=False)()