79 lines
2.7 KiB
Python
79 lines
2.7 KiB
Python
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
from sqlalchemy.orm import sessionmaker, declarative_base
|
|
from sqlalchemy.exc import OperationalError, SQLAlchemyError
|
|
import asyncio
|
|
import logging
|
|
from ..kangdaApi.parseConfig import parse_config
|
|
from .config import settings
|
|
|
|
# import yaml
|
|
|
|
# config_path = "app/config/config.yaml"
|
|
|
|
# config = parse_config(config_path)
|
|
|
|
# config_kangda = config["kangda"]
|
|
|
|
# print("sssss", config_kangda)
|
|
|
|
# 配置日志
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# 创建异步引擎
|
|
engine = create_async_engine(
|
|
f"mysql+aiomysql://{settings.DB_USER}:{settings.DB_PASSWORD}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}",
|
|
pool_size=settings.DB_POOL_SIZE,
|
|
max_overflow=settings.DB_MAX_OVERFLOW,
|
|
pool_timeout=settings.DB_POOL_TIMEOUT,
|
|
pool_recycle=settings.DB_POOL_RECYCLE,
|
|
pool_pre_ping=settings.DB_POOL_PRE_PING,
|
|
echo=settings.DB_ECHO
|
|
)
|
|
|
|
# engine = create_async_engine(
|
|
# f"mysql+aiomysql://{config_kangda["DB_USER"]}:{config_kangda["DB_PASSWORD"]}@{config_kangda["DB_HOST"]}:{config_kangda["DB_PORT"]}/{config_kangda["DB_NAME"]}",
|
|
# pool_size=config_kangda["DB_POOL_SIZE"],
|
|
# max_overflow=config_kangda["DB_MAX_OVERFLOW"],
|
|
# pool_timeout=config_kangda["DB_POOL_TIMEOUT"],
|
|
# pool_recycle=config_kangda["DB_POOL_RECYCLE"],
|
|
# echo=False
|
|
# )
|
|
|
|
# 创建异步会话工厂, expire_on_commit 禁用提交后过期对象--> 提交后原对象仍然可以继续使用.
|
|
async_session = sessionmaker(
|
|
engine, class_=AsyncSession, expire_on_commit=False
|
|
)
|
|
|
|
# 创建基类
|
|
Base = declarative_base()
|
|
|
|
# 获取数据库会话
|
|
async def get_db():
|
|
max_retries = 3
|
|
retry_delay = 5 # 重试延迟(秒)
|
|
|
|
for attempt in range(max_retries):
|
|
try:
|
|
async with async_session() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception as e:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close()
|
|
break # 如果成功,跳出重试循环
|
|
|
|
except (OperationalError, SQLAlchemyError) as e:
|
|
if attempt < max_retries - 1: # 如果不是最后一次尝试
|
|
logger.warning(f"数据库连接失败 (尝试 {attempt + 1}/{max_retries}): {str(e)}")
|
|
await asyncio.sleep(retry_delay)
|
|
continue
|
|
else:
|
|
logger.error(f"数据库连接失败,已达到最大重试次数: {str(e)}")
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"未知错误: {str(e)}")
|
|
raise |