/
authserver.go
63 lines (52 loc) · 1.01 KB
/
authserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package authcache
import (
"sort"
"sync"
"sync/atomic"
"time"
)
// AuthServer type
type AuthServer struct {
Host string
Rtt int64
Count int64
}
// NewAuthServer return a server
func NewAuthServer(host string) *AuthServer {
return &AuthServer{
Host: host,
}
}
func (a *AuthServer) String() string {
if a.Count == 0 {
a.Count = 1
}
return "host:" + a.Host + " rtt:" + (time.Duration(a.Rtt) / time.Duration(a.Count)).Round(time.Millisecond).String()
}
// AuthServers type
type AuthServers struct {
sync.RWMutex
called int32
List []*AuthServer
}
// TrySort if necessary sort servers by rtt
func (s *AuthServers) TrySort() bool {
atomic.AddInt32(&s.called, 1)
if atomic.LoadInt32(&s.called)%20 == 0 {
s.Lock()
for _, s := range s.List {
if s.Count > 0 {
// average rtt
s.Rtt = s.Rtt / s.Count
s.Count = 1
}
}
sort.Slice(s.List, func(i, j int) bool {
return s.List[i].Rtt < s.List[j].Rtt
})
s.Unlock()
atomic.StoreInt32(&s.called, 0)
return true
}
return false
}