From 8b788f5f84c9125ea29eb5fbc7b6871f42ce385a Mon Sep 17 00:00:00 2001 From: Lykin <137850705+tiny-craft@users.noreply.github.com> Date: Tue, 8 Apr 2025 16:44:05 +0800 Subject: [PATCH] pref: redesign the throttle of monitor --- backend/services/monitor_service.go | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/backend/services/monitor_service.go b/backend/services/monitor_service.go index 4ed31fa..6c960d9 100644 --- a/backend/services/monitor_service.go +++ b/backend/services/monitor_service.go @@ -100,8 +100,10 @@ func (c *monitorService) StartMonitor(server string) (resp types.JSResp) { } func (c *monitorService) processMonitor(mutex *sync.Mutex, ch <-chan string, closeCh <-chan struct{}, cmd *redis.MonitorCmd, eventName string) { - lastEmitTime := time.Now().Add(-1 * time.Minute) cache := make([]string, 0, 1000) + ticker := time.NewTicker(1 * time.Second) + defer ticker.Stop() + for { select { case data := <-ch: @@ -110,14 +112,23 @@ func (c *monitorService) processMonitor(mutex *sync.Mutex, ch <-chan string, clo mutex.Lock() defer mutex.Unlock() cache = append(cache, data) - if time.Now().Sub(lastEmitTime) > 1*time.Second || len(cache) > 300 { + if len(cache) > 300 { runtime.EventsEmit(c.ctx, eventName, cache) cache = cache[:0:cap(cache)] - lastEmitTime = time.Now() } }() } + case <-ticker.C: + func() { + mutex.Lock() + defer mutex.Unlock() + if len(cache) > 0 { + runtime.EventsEmit(c.ctx, eventName, cache) + cache = cache[:0:cap(cache)] + } + }() + case <-closeCh: // monitor stopped cmd.Stop()