Przeglądaj źródła

fix:数据库超时错误处理

tanjingyu 1 tydzień temu
rodzic
commit
0e22f85281
2 zmienionych plików z 16 dodań i 2 usunięć
  1. 9 1
      app/database.py
  2. 7 1
      app/main.py

+ 9 - 1
app/database.py

@@ -3,7 +3,15 @@ from sqlalchemy.ext.declarative import declarative_base
 from sqlalchemy.orm import sessionmaker
 from app.config import settings
 
-engine = create_engine(settings.DATABASE_URL)
+# 配置连接池参数以避免连接丢失问题
+engine = create_engine(
+    settings.DATABASE_URL,
+    pool_pre_ping=True,  # 连接前测试连接是否有效
+    pool_recycle=300,    # 每5分钟重新创建连接
+    pool_size=10,        # 连接池大小
+    max_overflow=20,     # 最大溢出连接数
+    echo=False           # 关闭SQL日志(生产环境)
+)
 SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
 
 Base = declarative_base()

+ 7 - 1
app/main.py

@@ -33,8 +33,14 @@ async def process_webhook_task(payload: dict):
         await service.process_webhook(payload)
     except Exception as e:
         logger.error(f"Webhook processing failed: {e}", exc_info=True)
+        # 确保在异常情况下也能正确关闭数据库连接
+        if hasattr(e, '__cause__') and 'Lost connection' in str(e) or 'MySQL server has gone away' in str(e):
+            logger.warning("MySQL connection lost, the pool should auto-reconnect due to pool_pre_ping=True")
     finally:
-        db.close()
+        try:
+            db.close()
+        except Exception as close_error:
+            logger.error(f"Error closing database session: {close_error}")
 
 
 def build_file_tree(files: List[DataFile]) -> list: