fix: MySQL 连���池添加重试逻辑

- 最多重试 30 次,每次间隔 2 秒
- 解决 MySQL 容器启动慢导致的连接失败问题
- 添加 import time 模块

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
lzh
2026-01-23 21:41:02 +08:00
parent 4c22a137cf
commit cd27ecf7d0

View File

@@ -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