deliveryman-api/app/api/endpoints/health.py
2025-03-10 20:18:52 +08:00

63 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from sqlalchemy import text
from app.models.database import get_db, get_active_sessions_count, get_long_running_sessions
from app.core.response import success_response, ResponseModel
from app.core.db_monitor import DBConnectionMonitor
router = APIRouter()
@router.get("/health", response_model=ResponseModel)
async def health_check(db: Session = Depends(get_db)):
"""健康检查端点检查API和数据库连接状态"""
# 尝试执行简单查询以验证数据库连接
try:
db.execute(text("SELECT 1")).scalar()
db_status = "healthy"
except Exception as e:
db_status = f"unhealthy: {str(e)}"
# 获取连接池状态和性能统计
all_stats = DBConnectionMonitor.get_all_stats()
# 获取活跃会话信息
active_sessions_count = get_active_sessions_count()
long_running_sessions = get_long_running_sessions(threshold_seconds=30)
return success_response(data={
"status": "ok",
"database": {
"status": db_status,
"connection_pool": all_stats["connection_pool"],
"active_sessions": active_sessions_count,
"long_running_sessions": len(long_running_sessions)
}
})
@router.get("/stats", response_model=ResponseModel)
async def performance_stats(
include_slow_queries: bool = Query(False, description="是否包含慢查询记录"),
include_long_sessions: bool = Query(False, description="是否包含长时间运行的会话详情"),
db: Session = Depends(get_db)
):
"""获取详细的性能统计信息"""
# 获取所有统计信息
all_stats = DBConnectionMonitor.get_all_stats()
# 如果不需要包含慢查询记录,则移除它们以减少响应大小
if not include_slow_queries and "slow_queries" in all_stats["performance_stats"]:
all_stats["performance_stats"]["slow_queries_count"] = len(all_stats["performance_stats"]["slow_queries"])
del all_stats["performance_stats"]["slow_queries"]
# 添加会话信息
all_stats["sessions"] = {
"active_count": get_active_sessions_count()
}
# 如果需要包含长时间运行的会话详情
if include_long_sessions:
all_stats["sessions"]["long_running"] = get_long_running_sessions(threshold_seconds=30)
else:
all_stats["sessions"]["long_running_count"] = len(get_long_running_sessions(threshold_seconds=30))
return success_response(data=all_stats)