From cd27ecf7d052011aeeb6dbba4474c6e6ecd8ba91 Mon Sep 17 00:00:00 2001 From: lzh Date: Fri, 23 Jan 2026 21:41:02 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20MySQL=20=E8=BF=9E=EF=BF=BD=EF=BF=BD?= =?UTF-8?q?=EF=BF=BD=E6=B1=A0=E6=B7=BB=E5=8A=A0=E9=87=8D=E8=AF=95=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 最多重试 30 次,每次间隔 2 秒 - 解决 MySQL 容器启动慢导致的连接失败问题 - 添加 import time 模块 Co-Authored-By: Claude Opus 4.5 --- src/vitals/core/database.py | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) 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