package main import ( "github.com/gin-gonic/gin" "net/http" "strconv" "time" ) // SQLHealthController SQL健康监控控制器 type SQLHealthController struct{} // NewSQLHealthController 创建SQL健康监控控制器 func NewSQLHealthController() *SQLHealthController { return &SQLHealthController{} } // GetSQLStats 获取SQL执行统计信息 func (shc *SQLHealthController) GetSQLStats(c *gin.Context) { if globalSQLMonitor == nil { c.JSON(http.StatusServiceUnavailable, gin.H{ "error": "SQL监控器未初始化", }) return } stats := globalSQLMonitor.GetStats() c.JSON(http.StatusOK, gin.H{ "status": "success", "data": stats, "timestamp": time.Now().Format("2006-01-02 15:04:05"), }) } // GetRecentSQLRecords 获取最近的SQL执行记录 func (shc *SQLHealthController) GetRecentSQLRecords(c *gin.Context) { if globalSQLMonitor == nil { c.JSON(http.StatusServiceUnavailable, gin.H{ "error": "SQL监控器未初始化", }) return } // 获取limit参数,默认50条 limitStr := c.DefaultQuery("limit", "50") limit, err := strconv.Atoi(limitStr) if err != nil || limit <= 0 { limit = 50 } if limit > 500 { limit = 500 // 最大限制500条 } records := globalSQLMonitor.GetRecentRecords(limit) c.JSON(http.StatusOK, gin.H{ "status": "success", "data": gin.H{ "records": records, "count": len(records), "limit": limit, }, "timestamp": time.Now().Format("2006-01-02 15:04:05"), }) } // GetSlowQueries 获取慢查询 func (shc *SQLHealthController) GetSlowQueries(c *gin.Context) { if globalSQLMonitor == nil { c.JSON(http.StatusServiceUnavailable, gin.H{ "error": "SQL监控器未初始化", }) return } // 获取阈值参数,默认1000ms thresholdStr := c.DefaultQuery("threshold", "1000") threshold, err := strconv.ParseInt(thresholdStr, 10, 64) if err != nil || threshold <= 0 { threshold = 1000 } slowQueries := globalSQLMonitor.GetSlowQueries(threshold) c.JSON(http.StatusOK, gin.H{ "status": "success", "data": gin.H{ "slow_queries": slowQueries, "count": len(slowQueries), "threshold_ms": threshold, }, "timestamp": time.Now().Format("2006-01-02 15:04:05"), }) } // GetFailedQueries 获取失败的查询 func (shc *SQLHealthController) GetFailedQueries(c *gin.Context) { if globalSQLMonitor == nil { c.JSON(http.StatusServiceUnavailable, gin.H{ "error": "SQL监控器未初始化", }) return } failedQueries := globalSQLMonitor.GetFailedQueries() c.JSON(http.StatusOK, gin.H{ "status": "success", "data": gin.H{ "failed_queries": failedQueries, "count": len(failedQueries), }, "timestamp": time.Now().Format("2006-01-02 15:04:05"), }) } // ClearSQLRecords 清空SQL记录 func (shc *SQLHealthController) ClearSQLRecords(c *gin.Context) { if globalSQLMonitor == nil { c.JSON(http.StatusServiceUnavailable, gin.H{ "error": "SQL监控器未初始化", }) return } globalSQLMonitor.ClearRecords() c.JSON(http.StatusOK, gin.H{ "status": "success", "message": "SQL记录已清空", "timestamp": time.Now().Format("2006-01-02 15:04:05"), }) } // GetSQLHealthDashboard 获取SQL健康监控仪表板 func (shc *SQLHealthController) GetSQLHealthDashboard(c *gin.Context) { dashboardHTML := `