fix: 捕获更多断线异常并优化重试逻辑,确保更稳健的数据库连接

This commit is contained in:
晓丰 2025-07-14 19:08:36 +08:00
parent f11e151832
commit 6c49ef042e

12
DB.py
View File

@ -94,8 +94,7 @@ video_author = Table(
def mysql_retry(max_retries: int = 3, base_delay: float = 2.0):
"""
装饰器工厂捕获 InterfaceError 后断线重连并重试
重试间隔按指数级增长base_delay * 2**(attempt-1)
装饰器捕获断线异常InterfaceError OperationalError: 2013后尝试重连指数回退重试
"""
def decorator(fn):
@ -103,16 +102,17 @@ def mysql_retry(max_retries: int = 3, base_delay: float = 2.0):
def wrapper(self, *args, **kwargs):
for attempt in range(1, max_retries + 1):
try:
# 确保连接存活reconnect=True 会在 ping 失败时重连
self.conn.ping(reconnect=True)
return fn(self, *args, **kwargs)
except pymysql.InterfaceError as e:
except (pymysql.InterfaceError, pymysql.OperationalError) as e:
if isinstance(e, pymysql.OperationalError) and e.args[0] != 2013:
raise # 只处理 2013其他 OperationalError 抛出
wait = base_delay * (2 ** (attempt - 1))
logger.info(f"[MySQL][{fn.__name__}] 第{attempt}次 InterfaceError{e},等待 {wait:.1f}s 后重连…")
logger.warning(f"[MySQL][{fn.__name__}] 第{attempt}重试(断开连接:{e},等待 {wait:.1f}s 后重连…")
time.sleep(wait)
self._reconnect_mysql()
if attempt == max_retries:
logger.info("[MySQL] 重试多次仍失败,抛出异常")
logger.error("[MySQL] 重试多次仍失败,抛出异常")
raise
return wrapper