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.
This commit is contained in:
wood chen 2024-12-05 10:30:10 +08:00
parent ef3bc0c5a6
commit c71da4c1fe

View File

@ -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
}