package performance import ( "context" "runtime" "time" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/os/gtime" ) // Monitor 性能监控器 type Monitor struct { startTime time.Time ctx context.Context } // NewMonitor 创建性能监控器 func NewMonitor(ctx context.Context) *Monitor { return &Monitor{ startTime: time.Now(), ctx: ctx, } } // GetExecutionTime 获取执行时间 func (m *Monitor) GetExecutionTime() time.Duration { return time.Since(m.startTime) } // LogPerformance 记录性能信息 func (m *Monitor) LogPerformance(operation string) { duration := m.GetExecutionTime() // 记录性能日志 g.Log().Info(m.ctx, "Performance Monitor", g.Map{ "operation": operation, "duration": duration.String(), "timestamp": gtime.Now().String(), }) // 如果执行时间超过阈值,记录警告 if duration > time.Second*2 { g.Log().Warning(m.ctx, "Slow Operation Detected", g.Map{ "operation": operation, "duration": duration.String(), "threshold": "2s", }) } } // GetMemoryUsage 获取内存使用情况 func GetMemoryUsage() map[string]interface{} { var m runtime.MemStats runtime.ReadMemStats(&m) return map[string]interface{}{ "alloc": bToMb(m.Alloc), // 当前分配的内存 "total_alloc": bToMb(m.TotalAlloc), // 总分配的内存 "sys": bToMb(m.Sys), // 系统内存 "num_gc": m.NumGC, // GC次数 "goroutines": runtime.NumGoroutine(), // 协程数量 } } // GetSystemInfo 获取系统信息 func GetSystemInfo() map[string]interface{} { return map[string]interface{}{ "go_version": runtime.Version(), "go_os": runtime.GOOS, "go_arch": runtime.GOARCH, "cpu_count": runtime.NumCPU(), "goroutines": runtime.NumGoroutine(), "memory_usage": GetMemoryUsage(), } } // bToMb 字节转MB func bToMb(b uint64) uint64 { return b / 1024 / 1024 } // DatabasePerformanceMonitor 数据库性能监控 type DatabasePerformanceMonitor struct { slowQueryThreshold time.Duration } // NewDatabasePerformanceMonitor 创建数据库性能监控器 func NewDatabasePerformanceMonitor() *DatabasePerformanceMonitor { return &DatabasePerformanceMonitor{ slowQueryThreshold: time.Millisecond * 500, // 500ms慢查询阈值 } } // LogSlowQuery 记录慢查询 func (d *DatabasePerformanceMonitor) LogSlowQuery(ctx context.Context, sql string, duration time.Duration, args ...interface{}) { if duration > d.slowQueryThreshold { g.Log().Warning(ctx, "Slow Query Detected", g.Map{ "sql": sql, "duration": duration.String(), "args": args, "threshold": d.slowQueryThreshold.String(), }) } } // APIPerformanceMonitor API性能监控 type APIPerformanceMonitor struct { requestCount map[string]int64 responseTime map[string][]time.Duration } // NewAPIPerformanceMonitor 创建API性能监控器 func NewAPIPerformanceMonitor() *APIPerformanceMonitor { return &APIPerformanceMonitor{ requestCount: make(map[string]int64), responseTime: make(map[string][]time.Duration), } } // RecordRequest 记录请求 func (a *APIPerformanceMonitor) RecordRequest(endpoint string, duration time.Duration) { a.requestCount[endpoint]++ a.responseTime[endpoint] = append(a.responseTime[endpoint], duration) // 保持最近100次请求的记录 if len(a.responseTime[endpoint]) > 100 { a.responseTime[endpoint] = a.responseTime[endpoint][1:] } } // GetStats 获取统计信息 func (a *APIPerformanceMonitor) GetStats(endpoint string) map[string]interface{} { times := a.responseTime[endpoint] if len(times) == 0 { return map[string]interface{}{ "request_count": a.requestCount[endpoint], "avg_time": 0, "min_time": 0, "max_time": 0, } } var total, min, max time.Duration min = times[0] max = times[0] for _, t := range times { total += t if t < min { min = t } if t > max { max = t } } return map[string]interface{}{ "request_count": a.requestCount[endpoint], "avg_time": (total / time.Duration(len(times))).String(), "min_time": min.String(), "max_time": max.String(), "sample_count": len(times), } } // CachePerformanceMonitor 缓存性能监控 type CachePerformanceMonitor struct { hitCount int64 missCount int64 } // NewCachePerformanceMonitor 创建缓存性能监控器 func NewCachePerformanceMonitor() *CachePerformanceMonitor { return &CachePerformanceMonitor{} } // RecordHit 记录缓存命中 func (c *CachePerformanceMonitor) RecordHit() { c.hitCount++ } // RecordMiss 记录缓存未命中 func (c *CachePerformanceMonitor) RecordMiss() { c.missCount++ } // GetHitRate 获取缓存命中率 func (c *CachePerformanceMonitor) GetHitRate() float64 { total := c.hitCount + c.missCount if total == 0 { return 0 } return float64(c.hitCount) / float64(total) * 100 } // GetStats 获取缓存统计 func (c *CachePerformanceMonitor) GetStats() map[string]interface{} { return map[string]interface{}{ "hit_count": c.hitCount, "miss_count": c.missCount, "total_count": c.hitCount + c.missCount, "hit_rate": c.GetHitRate(), } }