61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"go.uber.org/zap"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// StartPoolStatsLogger 周期性记录连接池压力,便于区分 SQL 慢和连接排队。
|
|
func StartPoolStatsLogger(ctx context.Context, db *gorm.DB, logger *zap.Logger, interval time.Duration) {
|
|
if db == nil || logger == nil {
|
|
return
|
|
}
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
return
|
|
}
|
|
if interval <= 0 {
|
|
interval = 30 * time.Second
|
|
}
|
|
var lastWaitCount int64
|
|
logStats := func() {
|
|
stats := sqlDB.Stats()
|
|
waitDelta := stats.WaitCount - lastWaitCount
|
|
lastWaitCount = stats.WaitCount
|
|
fields := []zap.Field{
|
|
zap.Int("open_connections", stats.OpenConnections),
|
|
zap.Int("in_use", stats.InUse),
|
|
zap.Int("idle", stats.Idle),
|
|
zap.Int("max_open_connections", stats.MaxOpenConnections),
|
|
zap.Int64("wait_count", stats.WaitCount),
|
|
zap.Float64("wait_duration_ms", float64(stats.WaitDuration.Microseconds())/1000),
|
|
zap.Int64("max_idle_closed", stats.MaxIdleClosed),
|
|
zap.Int64("max_idle_time_closed", stats.MaxIdleTimeClosed),
|
|
zap.Int64("max_lifetime_closed", stats.MaxLifetimeClosed),
|
|
}
|
|
highPressure := waitDelta > 0 ||
|
|
(stats.MaxOpenConnections > 0 && stats.InUse >= stats.MaxOpenConnections*4/5)
|
|
if highPressure {
|
|
logger.Warn("数据库连接池压力", fields...)
|
|
return
|
|
}
|
|
logger.Info("数据库连接池状态", fields...)
|
|
}
|
|
logStats()
|
|
go func() {
|
|
ticker := time.NewTicker(interval)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
logStats()
|
|
}
|
|
}
|
|
}()
|
|
}
|