GORM 连接池监控
GORM 提供 Stats 方法实时获取连接池状态,便于监控与排查性能问题。
Stats 方法
核心方法
Go
sqlDB, _ := db.DB()
stats := sqlDB.Stats()
返回结构体
Go
type DBStats struct {
MaxOpenConnections int // 最大允许连接数
// 连接池状态
OpenConnections int // 当前打开的连接数
InUse int // 正在使用的连接数
Idle int // 空闲连接数
// 等待与阻塞
WaitCount int64 // 等待连接的总次数
WaitDuration time.Duration // 等待总耗时
MaxIdleClosed int64 // 因空闲超时而关闭的连接数
MaxIdleTimeClosed int64 // 因 ConnMaxIdleTime 关闭的连接数
MaxLifetimeClosed int64 // 因 ConnMaxLifetime 关闭的连接数
}
监控示例
打印连接池状态
Go
func printDBStats(db *gorm.DB) {
sqlDB, _ := db.DB()
stats := sqlDB.Stats()
fmt.Printf("打开连接: %d (最大: %d)\n", stats.OpenConnections, stats.MaxOpenConnections)
fmt.Printf("使用中: %d | 空闲: %d\n", stats.InUse, stats.Idle)
fmt.Printf("等待次数: %d | 等待耗时: %v\n", stats.WaitCount, stats.WaitDuration)
}
定时监控
Go
go func() {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for range ticker.C {
stats := sqlDB.Stats()
if stats.WaitCount > 0 {
log.Printf("连接池等待过多: %+v", stats)
}
}
}()
关键指标解读
| 指标 | 说明 | 告警阈值 |
|---|---|---|
InUse | 正在使用的连接数 | 接近 MaxOpenConns |
WaitCount | 等待连接的请求数 | 持续增长 |
WaitDuration | 等待总耗时 | 平均等待 > 100ms |
Idle | 空闲连接数 | 远大于 MaxIdleConns |
告警实践
连接池满检测
Go
func checkPoolExhaustion(stats sql.DBStats) bool {
return stats.InUse >= stats.MaxOpenConnections*9/10
}
等待过多检测
Go
func checkWaitThreshold(stats sql.DBStats) bool {
if stats.WaitCount > 100 {
avgWait := stats.WaitDuration / time.Duration(stats.WaitCount)
return avgWait > 50*time.Millisecond
}
return false
}
注意事项
Stats返回的是调用时刻的快照,高并发场景数据可能快速变化。
WaitCount与WaitDuration为累计值,需定期采样计算速率。
连接池满时应检查
MaxOpenConns是否合理,而非盲目增大。
要点总结
Stats方法返回连接池实时状态,包含连接数、等待、关闭等指标- 核心指标包括
InUse(使用中)、WaitCount(等待数)、Idle(空闲) - 可配合定时任务采样,检测连接池耗尽与等待异常
- 告警应结合业务负载设定合理阈值
- 连接池监控是排查数据库性能问题的重要手段
存放路径:D:\git2\jwdev\articles\GORM\进阶\数据库连接池管理\连接池监控.md
📝 发现内容有误?点击此处直接编辑