5
5
6
6
from fastapi import Depends
7
7
from sqlalchemy import URL
8
- from sqlalchemy .ext .asyncio import AsyncSession , async_sessionmaker , create_async_engine
8
+ from sqlalchemy .ext .asyncio import AsyncEngine , AsyncSession , async_sessionmaker , create_async_engine
9
9
10
10
from backend .common .log import log
11
11
from backend .common .model import MappedBase
@@ -32,11 +32,23 @@ def create_database_url(unittest: bool = False) -> URL:
32
32
return url
33
33
34
34
35
- def create_engine_and_session (url : str | URL ):
35
+ def create_async_engine_and_session (url : str | URL ) -> tuple [ AsyncEngine , async_sessionmaker [ AsyncSession ]] :
36
36
"""创建数据库引擎和 Session"""
37
37
try :
38
38
# 数据库引擎
39
- engine = create_async_engine (url , echo = settings .DATABASE_ECHO , future = True , pool_pre_ping = True )
39
+ engine = create_async_engine (
40
+ url ,
41
+ echo = settings .DATABASE_ECHO ,
42
+ echo_pool = settings .DATABASE_POOL_ECHO ,
43
+ future = True ,
44
+ # 中等并发
45
+ pool_size = 10 , # 低:- 高:+
46
+ max_overflow = 20 , # 低:- 高:+
47
+ pool_timeout = 30 , # 低:+ 高:-
48
+ pool_recycle = 3600 , # 低:+ 高:-
49
+ pool_pre_ping = True , # 低:False 高:True
50
+ pool_use_lifo = False , # 低:False 高:True
51
+ )
40
52
# log.success('数据库连接成功')
41
53
except Exception as e :
42
54
log .error ('❌ 数据库链接失败 {}' , e )
@@ -52,7 +64,7 @@ async def get_db():
52
64
yield session
53
65
54
66
55
- async def create_table ():
67
+ async def create_table () -> None :
56
68
"""创建数据库表"""
57
69
async with async_engine .begin () as coon :
58
70
await coon .run_sync (MappedBase .metadata .create_all )
@@ -64,6 +76,6 @@ def uuid4_str() -> str:
64
76
65
77
66
78
SQLALCHEMY_DATABASE_URL = create_database_url ()
67
- async_engine , async_db_session = create_engine_and_session (SQLALCHEMY_DATABASE_URL )
79
+ async_engine , async_db_session = create_async_engine_and_session (SQLALCHEMY_DATABASE_URL )
68
80
# Session Annotated
69
81
CurrentSession = Annotated [AsyncSession , Depends (get_db )]
0 commit comments