Files

58 lines
1.3 KiB
Python
Raw Permalink Normal View History

"""
MySQL 连接池管理(aiomysql)
用法:
await init_pool() # 应用启动时调用
async with acquire() as conn:
...
await close_pool() # 应用关闭时调用
连接池开启 autocommit,单条语句自动提交;需要事务时显式调用 conn.begin() / conn.commit()。
"""
from contextlib import asynccontextmanager
from typing import Optional
import aiomysql
from config import MYSQL_DB, MYSQL_HOST, MYSQL_PASSWORD, MYSQL_PORT, MYSQL_USER
_pool: Optional[aiomysql.Pool] = None
async def init_pool() -> None:
"""创建全局连接池"""
global _pool
_pool = await aiomysql.create_pool(
host=MYSQL_HOST,
port=MYSQL_PORT,
user=MYSQL_USER,
password=MYSQL_PASSWORD,
db=MYSQL_DB,
charset="utf8mb4",
autocommit=True,
minsize=1,
maxsize=10,
)
async def close_pool() -> None:
"""关闭连接池"""
global _pool
if _pool is not None:
_pool.close()
await _pool.wait_closed()
_pool = None
def get_pool() -> aiomysql.Pool:
if _pool is None:
raise RuntimeError("MySQL 连接池未初始化,请先调用 init_pool()")
return _pool
@asynccontextmanager
async def acquire():
"""从连接池借出一个连接"""
async with get_pool().acquire() as conn:
yield conn