diff --git a/src/vitals/core/database.py b/src/vitals/core/database.py index 03ca896..25cd0f8 100644 --- a/src/vitals/core/database.py +++ b/src/vitals/core/database.py @@ -2,6 +2,7 @@ import json import os +import time from contextlib import contextmanager from datetime import date, time, datetime, timedelta from typing import Optional @@ -28,16 +29,33 @@ def get_mysql_config() -> dict: def init_connection_pool(): - """初始化数据库连接池""" + """初始化数据库连接池(带重试)""" global _connection_pool if _connection_pool is None: config = get_mysql_config() - _connection_pool = pooling.MySQLConnectionPool( - pool_name="vitals_pool", - pool_size=5, - pool_reset_session=True, - **config - ) + max_retries = 30 + retry_delay = 2 + + for attempt in range(max_retries): + try: + _connection_pool = pooling.MySQLConnectionPool( + pool_name="vitals_pool", + pool_size=5, + pool_reset_session=True, + **config + ) + # 测试连接 + conn = _connection_pool.get_connection() + conn.close() + print(f"[Vitals] MySQL 连接池初始化成功") + return _connection_pool + except Exception as e: + if attempt < max_retries - 1: + print(f"[Vitals] MySQL 连接失败,{retry_delay}秒后重试... ({attempt + 1}/{max_retries}): {e}") + time.sleep(retry_delay) + else: + print(f"[Vitals] MySQL 连接失败,已重试 {max_retries} 次") + raise return _connection_pool