Skip to content

Commit

Permalink
fix: optimize for ping result expire
Browse files Browse the repository at this point in the history
  • Loading branch information
tiancheng91 committed Jan 16, 2023
1 parent bd2d165 commit 53ff3fb
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions selector.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ type FastestFilter struct {

pinger *net.Dialer
pingResult map[int]int
pingResultTTL map[int]int
pingResultTTL map[int]int64

topCount int
}
Expand All @@ -227,7 +227,7 @@ func NewFastestFilter(pingTimeOut int, topCount int) *FastestFilter {
mu: sync.Mutex{},
pinger: &net.Dialer{Timeout: time.Millisecond * time.Duration(pingTimeOut)},
pingResult: make(map[int]int, 0),
pingResultTTL: make(map[int]int, 0),
pingResultTTL: make(map[int]int64, 0),
topCount: topCount,
}
}
Expand All @@ -240,19 +240,22 @@ func (f *FastestFilter) Filter(nodes []Node) []Node {

// get latency with ttl cache
now := time.Now().Unix()
r := rand.New(rand.NewSource(time.Now().UnixNano()))

var getNodeLatency = func(node Node) int {
if now-int64(f.pingResultTTL[node.ID]) > 60*5 {
if f.pingResultTTL[node.ID] < now {
f.mu.Lock()
f.pingResultTTL[node.ID] = int(now)
f.pingResultTTL[node.ID] = now + 5 // tmp
defer f.mu.Unlock()

// get latency
go func(node Node) {
latency := f.doTcpPing(node.Addr)
ttl := 300 - int64(60*r.Float64())

f.mu.Lock()
f.pingResult[node.ID] = latency
f.pingResultTTL[node.ID] = int(time.Now().Unix())
f.pingResultTTL[node.ID] = ttl
defer f.mu.Unlock()
}(node)
}
Expand Down

0 comments on commit 53ff3fb

Please sign in to comment.