Add tags cache to app.proxyman.ohm.Select() (#2927)

* Add tags cache to ohm.Select().

* Refactor round-robin.

* Fix a bug.

---------

Co-authored-by: nobody <nobody@nowhere.mars>
This commit is contained in:
nobody 2024-01-12 23:36:48 +08:00 committed by GitHub
parent 0ea2a50264
commit 7f7f57d3b6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 24 deletions

View file

@ -2,7 +2,6 @@ package router
import (
"context"
reflect "reflect"
sync "sync"
"github.com/xtls/xray-core/common/dice"
@ -26,35 +25,20 @@ func (s *RandomStrategy) PickOutbound(tags []string) string {
}
type RoundRobinStrategy struct {
mu sync.Mutex
tags []string
index int
roundRobin *RoundRobinStrategy
}
func NewRoundRobin(tags []string) *RoundRobinStrategy {
return &RoundRobinStrategy{
tags: tags,
}
}
func (r *RoundRobinStrategy) NextTag() string {
r.mu.Lock()
defer r.mu.Unlock()
tags := r.tags[r.index]
r.index = (r.index + 1) % len(r.tags)
return tags
mu sync.Mutex
index int
}
func (s *RoundRobinStrategy) PickOutbound(tags []string) string {
if len(tags) == 0 {
n := len(tags)
if n == 0 {
panic("0 tags")
}
if s.roundRobin == nil || !reflect.DeepEqual(s.roundRobin.tags, tags) {
s.roundRobin = NewRoundRobin(tags)
}
tag := s.roundRobin.NextTag()
s.mu.Lock()
defer s.mu.Unlock()
tag := tags[s.index%n]
s.index = (s.index + 1) % n
return tag
}