From c71da4c1fec04ff68d6d9618518eff4f6139f7a5 Mon Sep 17 00:00:00 2001 From: wood chen Date: Thu, 5 Dec 2024 10:30:10 +0800 Subject: [PATCH] feat(metrics): initialize cache and object pool in metrics collector - Added cache initialization to enhance performance and data retrieval efficiency. - Introduced an object pool for managing statistics, optimizing memory usage during metrics processing. - Improved code organization by clarifying initialization steps for cache and monitoring components. These changes enhance the metrics collector's efficiency and resource management, ensuring better performance in data handling. --- internal/metrics/collector.go | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/internal/metrics/collector.go b/internal/metrics/collector.go index 5e6329c..953bc33 100644 --- a/internal/metrics/collector.go +++ b/internal/metrics/collector.go @@ -71,6 +71,9 @@ func InitCollector(dbPath string, config *config.Config) error { db: db, } + // 先初始化 cache + globalCollector.cache = cache.NewCache(constants.CacheTTL) + // 在初始化时设置最后保存时间 lastSaveTime = time.Now() @@ -93,7 +96,7 @@ func InitCollector(dbPath string, config *config.Config) error { lastMetrics.TotalRequests, lastMetrics.TotalErrors, lastMetrics.TotalBytes) } - globalCollector.cache = cache.NewCache(constants.CacheTTL) + // 初始化监控器 globalCollector.monitor = monitor.NewMonitor(globalCollector) // 如果配置了飞书webhook,则启用飞书告警 @@ -104,6 +107,13 @@ func InitCollector(dbPath string, config *config.Config) error { log.Printf("Feishu alert enabled") } + // 初始化对象池 + globalCollector.statsPool = sync.Pool{ + New: func() interface{} { + return make(map[string]interface{}, 20) + }, + } + // 启动定时保存 go func() { time.Sleep(time.Duration(rand.Int63n(60)) * time.Second) @@ -163,12 +173,6 @@ func InitCollector(dbPath string, config *config.Config) error { log.Println("Database closed successfully") }) - globalCollector.statsPool = sync.Pool{ - New: func() interface{} { - return make(map[string]interface{}, 20) - }, - } - return nil }