@@ -154,51 +154,42 @@ func (v *apiV1) monitorHistoriesById(c *gin.Context) {
154154 if singleton .Conf .DatabaseType == "badger" {
155155 // BadgerDB 模式下使用 MonitorAPI,只查询最近7天的ICMP/TCP监控数据
156156 if singleton .MonitorAPI != nil {
157- // 极致性能优化:只获取最近1天的数据,大幅提高性能
157+ // 根本性性能优化:恢复3天数据,但优化查询方式
158158 endTime := time .Now ()
159- startTime := endTime .AddDate (0 , 0 , - 1 ) // 从3天减少到1天
159+ startTime := endTime .AddDate (0 , 0 , - 3 ) // 恢复3天数据
160160
161161 if db .DB != nil {
162+ // 性能优化:直接按服务器ID和时间范围查询,避免查询所有记录
162163 monitorOps := db .NewMonitorHistoryOps (db .DB )
163- allHistories , err := monitorOps .GetAllMonitorHistoriesInRange (startTime , endTime )
164- if err != nil {
165- log .Printf ("查询网络监控历史记录失败: %v" , err )
166- c .JSON (200 , []any {})
167- return
168- }
169164
170- // 性能优化: 预先获取监控配置,避免重复查询
165+ // 预先获取监控配置
171166 monitors := singleton .ServiceSentinelShared .Monitors ()
172167 monitorTypeMap := make (map [uint64 ]uint8 )
168+ icmpTcpMonitorIDs := []uint64 {}
173169 if monitors != nil {
174170 for _ , monitor := range monitors {
175171 monitorTypeMap [monitor .ID ] = monitor .Type
172+ if monitor .Type == model .TaskTypeICMPPing || monitor .Type == model .TaskTypeTCPPing {
173+ icmpTcpMonitorIDs = append (icmpTcpMonitorIDs , monitor .ID )
174+ }
176175 }
177176 }
178177
179- // 过滤出ICMP和TCP监控记录,限制数量
180- var networkHistories []* model.MonitorHistory
181- count := 0
182- maxRecords := 100 // 大幅减少记录数,提高性能
178+ log .Printf ("服务器 %d 的ICMP/TCP监控器ID列表: %v" , server .ID , icmpTcpMonitorIDs )
183179
184- log .Printf ("开始过滤服务器 %d 的监控历史记录,总记录数: %d" , server .ID , len (allHistories ))
180+ // 性能优化:直接查询指定服务器和监控器的记录
181+ var networkHistories []* model.MonitorHistory
185182
186- for _ , history := range allHistories {
187- if count >= maxRecords {
188- break
189- }
190- if history != nil && history .ServerID == server .ID {
191- if monitorType , exists := monitorTypeMap [history .MonitorID ]; exists &&
192- (monitorType == model .TaskTypeICMPPing || monitorType == model .TaskTypeTCPPing ) {
193- log .Printf ("找到ICMP/TCP监控记录: MonitorID=%d, ServerID=%d, Type=%d" ,
194- history .MonitorID , history .ServerID , monitorType )
195- networkHistories = append (networkHistories , history )
196- count ++
197- } else {
198- log .Printf ("跳过非ICMP/TCP监控记录: MonitorID=%d, ServerID=%d, Type=%d" ,
199- history .MonitorID , history .ServerID , monitorType )
200- }
183+ for _ , monitorID := range icmpTcpMonitorIDs {
184+ // 为每个监控器单独查询,避免全表扫描
185+ histories , err := monitorOps .GetMonitorHistoriesByServerAndMonitor (server .ID , monitorID , startTime , endTime , 200 )
186+ if err != nil {
187+ log .Printf ("查询监控器 %d 的历史记录失败: %v" , monitorID , err )
188+ continue
201189 }
190+
191+ log .Printf ("监控器 %d 在服务器 %d 上找到 %d 条记录" , monitorID , server .ID , len (histories ))
192+ networkHistories = append (networkHistories , histories ... )
202193 }
203194
204195 log .Printf ("服务器 %d 最终返回 %d 条ICMP/TCP监控记录" , server .ID , len (networkHistories ))
0 commit comments