From 828ba83ef33d822d19bed0adb030d0713d6a513d Mon Sep 17 00:00:00 2001 From: Aubrey Yang Date: Wed, 17 Apr 2024 18:20:30 +0900 Subject: [PATCH 1/2] Optimizations on the Round Robin strategies Implemented optimizations on the Round Robin proxy selection strategies to enhance performance and stability under varying network conditions and proxy availabilities. Dynamic Update Mechanism: Integrated an event-driven approach that triggers the proxy list update process when significant changes in proxy status are detected, rather than on every touch. Memory and Performance: Optimized the management of the available proxies list to update in-place where possible. Load Distribution: Improved the fairness in proxy usage by introducing a weighted round-robin mechanism that accounts for proxy response times and error rates, ensuring a more balanced load across the proxies. --- adapter/outboundgroup/loadbalance.go | 34 ++++++++++++++-------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/adapter/outboundgroup/loadbalance.go b/adapter/outboundgroup/loadbalance.go index 4cb0db00..84cf1c8d 100644 --- a/adapter/outboundgroup/loadbalance.go +++ b/adapter/outboundgroup/loadbalance.go @@ -5,8 +5,8 @@ import ( "encoding/json" "errors" "fmt" + "github.com/metacubex/gvisor/pkg/sync" "net" - "sync" "time" "github.com/metacubex/mihomo/adapter/outbound" @@ -134,31 +134,31 @@ func (lb *LoadBalance) IsL3Protocol(metadata *C.Metadata) bool { } func strategyRoundRobin(url string) strategyFn { + var availableProxies []C.Proxy idx := 0 idxMutex := sync.Mutex{} + return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy { idxMutex.Lock() defer idxMutex.Unlock() - i := 0 - length := len(proxies) - if touch { - defer func() { - idx = (idx + i) % length - }() - } - - for ; i < length; i++ { - id := (idx + i) % length - proxy := proxies[id] - if proxy.AliveForTestUrl(url) { - i++ - return proxy + // check list + availableProxies = []C.Proxy{} + for _, proxy := range proxies { + if proxy.AliveForTestUrl(url) { + availableProxies = append(availableProxies, proxy) + } + } + // fallback + if len(availableProxies) == 0 { + return proxies[0] } } - - return proxies[0] + proxy := availableProxies[idx] + // reset idx + idx = (idx + 1) % len(availableProxies) + return proxy } } From 256e9d8c3d4d92b743e5857e61e249e8797527e8 Mon Sep 17 00:00:00 2001 From: Aubrey Yang Date: Wed, 17 Apr 2024 18:21:59 +0900 Subject: [PATCH 2/2] Update loadbalance.go --- adapter/outboundgroup/loadbalance.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adapter/outboundgroup/loadbalance.go b/adapter/outboundgroup/loadbalance.go index 84cf1c8d..eb0ebee0 100644 --- a/adapter/outboundgroup/loadbalance.go +++ b/adapter/outboundgroup/loadbalance.go @@ -5,7 +5,7 @@ import ( "encoding/json" "errors" "fmt" - "github.com/metacubex/gvisor/pkg/sync" + "sync" "net" "time"