daShangDao_centerBook/md/sql_monitor_usage.md
2026-02-28 14:27:33 +08:00

253 lines
6.3 KiB
Markdown
Raw Permalink 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.

# SQL健康监控使用指南
## 概述
本项目已集成了简单而高效的SQL健康监控功能可以自动记录每条SQL语句的执行时间、成功状态和错误信息。
## 功能特性
- ✅ 自动记录SQL执行时间毫秒级精度
- ✅ 记录SQL执行成功/失败状态
- ✅ 记录错误信息和影响行数
- ✅ 支持慢查询检测
- ✅ 提供统计信息(成功率、平均耗时等)
- ✅ 提供Web仪表板实时监控
- ✅ 内存高效(可配置最大记录数)
## API接口
### 1. 获取SQL执行统计信息
```
GET /api/sql-health/stats
```
响应示例:
```json
{
"status": "success",
"data": {
"total_queries": 1250,
"success_queries": 1240,
"failed_queries": 10,
"success_rate": "99.20",
"avg_duration_ms": 45,
"max_duration_ms": 2300,
"min_duration_ms": 2,
"last_update": "2024-01-15 14:30:25"
},
"timestamp": "2024-01-15 14:30:25"
}
```
### 2. 获取最近的SQL执行记录
```
GET /api/sql-health/recent?limit=50
```
参数:
- `limit`: 返回记录数量默认50最大500
响应示例:
```json
{
"status": "success",
"data": {
"records": [
{
"id": 1001,
"query": "SELECT id, book_name FROM book_center WHERE vio_book = ? ORDER BY id DESC LIMIT ? OFFSET ?",
"duration_ms": 23,
"timestamp": "2024-01-15T14:30:25Z",
"success": true,
"error": "",
"endpoint": "/api/bookBase/GetBookBaseInfoOptimized",
"rows_affected": 0
}
],
"count": 50,
"limit": 50
},
"timestamp": "2024-01-15 14:30:25"
}
```
### 3. 获取慢查询
```
GET /api/sql-health/slow-queries?threshold=1000
```
参数:
- `threshold`: 慢查询阈值毫秒默认1000ms
### 4. 获取失败查询
```
GET /api/sql-health/failed-queries
```
### 5. 清空记录
```
POST /api/sql-health/clear
```
### 6. Web仪表板
```
GET /api/sql-health/dashboard
```
访问此URL可以查看实时的SQL健康监控仪表板。
## 在代码中使用SQL监控
### 1. 查询操作(返回多行)
```go
func (bc *BookCenterController) YourQueryMethod(c *gin.Context) {
query := "SELECT * FROM book_center WHERE category = ?"
endpoint := c.FullPath() // 获取当前接口路径
// 使用监控执行查询
rows, err := MonitorQuery(bc.db, query, endpoint, "小说")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "查询失败"})
return
}
defer rows.Close()
// 处理结果...
}
```
### 2. 单行查询操作
```go
func (bc *BookCenterController) GetBookByISBN(c *gin.Context) {
isbn := c.Query("isbn")
query := "SELECT id, book_name, author FROM book_center WHERE isbn = ?"
endpoint := c.FullPath()
// 使用监控执行单行查询
row := MonitorQueryRow(bc.db, query, endpoint, isbn)
var id int64
var bookName, author string
if err := row.Scan(&id, &bookName, &author); err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "图书不存在"})
return
}
// 返回结果...
}
```
### 3. 更新/插入/删除操作
```go
func (bc *BookCenterController) UpdateBook(c *gin.Context) {
query := "UPDATE book_center SET book_name = ? WHERE id = ?"
endpoint := c.FullPath()
// 使用监控执行更新操作
result, err := MonitorExec(bc.db, query, endpoint, "新书名", 123)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "更新失败"})
return
}
rowsAffected, _ := result.RowsAffected()
c.JSON(http.StatusOK, gin.H{
"message": "更新成功",
"rows_affected": rowsAffected,
})
}
```
## 监控配置
### 初始化配置
`main.go` 中的初始化:
```go
func main() {
// 初始化SQL监控器最多保存1000条记录
InitSQLMonitor(1000)
// ... 其他初始化代码
}
```
### 自定义配置
可以根据需要调整最大记录数:
```go
// 保存更多记录(适合高流量应用)
InitSQLMonitor(5000)
// 保存较少记录(适合内存受限环境)
InitSQLMonitor(500)
```
## 性能影响
- **内存占用**: 每条记录约占用200-500字节
- **CPU开销**: 每次SQL执行增加约0.1-0.5ms开销
- **并发安全**: 使用读写锁,支持高并发访问
- **自动清理**: 超过最大记录数时自动删除旧记录
## 监控指标说明
### 统计指标
- `total_queries`: 总查询数
- `success_queries`: 成功查询数
- `failed_queries`: 失败查询数
- `success_rate`: 成功率(百分比)
- `avg_duration_ms`: 平均执行时间(毫秒)
- `max_duration_ms`: 最大执行时间(毫秒)
- `min_duration_ms`: 最小执行时间(毫秒)
### 记录字段
- `id`: 记录唯一ID
- `query`: SQL查询语句
- `duration_ms`: 执行时间(毫秒)
- `timestamp`: 执行时间戳
- `success`: 是否成功
- `error`: 错误信息(如果有)
- `endpoint`: 调用的API接口
- `rows_affected`: 影响的行数仅适用于INSERT/UPDATE/DELETE
## 最佳实践
1. **接口标识**: 使用 `c.FullPath()` 作为endpoint参数便于追踪问题
2. **错误处理**: 监控函数会自动记录错误,无需额外处理
3. **性能优化**: 对于非关键查询,可以考虑不使用监控以减少开销
4. **定期清理**: 在生产环境中定期调用清理接口,避免内存占用过多
5. **阈值设置**: 根据业务需求调整慢查询阈值
## 故障排查
### 常见问题
1. **监控器未初始化**: 确保在main函数中调用了 `InitSQLMonitor()`
2. **记录不显示**: 检查是否使用了 `MonitorQuery` 等监控函数
3. **内存占用过高**: 减少最大记录数或定期清理记录
### 调试技巧
- 查看控制台日志,监控函数会输出详细的执行信息
- 使用仪表板实时查看SQL执行情况
- 通过API接口获取详细的统计信息
## 示例场景
### 场景1: 性能优化
通过监控发现某个查询平均耗时过长,可以:
1. 查看慢查询接口找到具体SQL
2. 分析SQL执行计划
3. 添加合适的索引
4. 重新监控验证优化效果
### 场景2: 错误排查
当出现数据库错误时,可以:
1. 查看失败查询接口
2. 分析错误信息和SQL语句
3. 定位问题原因
4. 修复后验证
### 场景3: 容量规划
通过长期监控数据:
1. 分析查询频率和耗时趋势
2. 评估数据库负载
3. 制定扩容计划