fix: 捕获更多断线异常并优化重试逻辑,确保更稳健的数据库连接
This commit is contained in:
parent
f11e151832
commit
6c49ef042e
12
DB.py
12
DB.py
@ -94,8 +94,7 @@ video_author = Table(
|
|||||||
|
|
||||||
def mysql_retry(max_retries: int = 3, base_delay: float = 2.0):
|
def mysql_retry(max_retries: int = 3, base_delay: float = 2.0):
|
||||||
"""
|
"""
|
||||||
装饰器工厂:捕获 InterfaceError 后断线重连并重试,
|
装饰器:捕获断线异常(InterfaceError 或 OperationalError: 2013)后尝试重连,指数回退重试。
|
||||||
重试间隔按指数级增长:base_delay * 2**(attempt-1) 秒。
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def decorator(fn):
|
def decorator(fn):
|
||||||
@ -103,16 +102,17 @@ def mysql_retry(max_retries: int = 3, base_delay: float = 2.0):
|
|||||||
def wrapper(self, *args, **kwargs):
|
def wrapper(self, *args, **kwargs):
|
||||||
for attempt in range(1, max_retries + 1):
|
for attempt in range(1, max_retries + 1):
|
||||||
try:
|
try:
|
||||||
# 确保连接存活,reconnect=True 会在 ping 失败时重连
|
|
||||||
self.conn.ping(reconnect=True)
|
self.conn.ping(reconnect=True)
|
||||||
return fn(self, *args, **kwargs)
|
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))
|
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)
|
time.sleep(wait)
|
||||||
self._reconnect_mysql()
|
self._reconnect_mysql()
|
||||||
if attempt == max_retries:
|
if attempt == max_retries:
|
||||||
logger.info("[MySQL] 重试多次仍失败,抛出异常")
|
logger.error("[MySQL] 重试多次仍失败,抛出异常")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
return wrapper
|
return wrapper
|
||||||
|
Loading…
x
Reference in New Issue
Block a user