-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleast_connections.go
75 lines (61 loc) · 1.2 KB
/
least_connections.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
64
65
66
67
68
69
70
71
72
73
74
75
package leastconnections
import (
"net/url"
"sync"
"github.com/pkg/errors"
)
// ErrServersNotExist is the error that servers dose not exists
var ErrServersNotExist = errors.New("servers dose not exist")
// LeastConnections is an interface for representing least-connections balancing.
type LeastConnections interface {
Next() (next *url.URL, done func())
}
type conn struct {
url *url.URL
cnt int
}
type leastConnections struct {
conns []conn
mu *sync.Mutex
}
// New initializes a new instance of LeastConnected
func New(urls []*url.URL) (LeastConnections, error) {
if len(urls) == 0 {
return nil, ErrServersNotExist
}
conns := make([]conn, len(urls))
for i := range conns {
conns[i] = conn{
url: urls[i],
cnt: 0,
}
}
return &leastConnections{
conns: conns,
mu: new(sync.Mutex),
}, nil
}
func (lc *leastConnections) Next() (*url.URL, func()) {
var (
min = -1
idx int
)
lc.mu.Lock()
for i, conn := range lc.conns {
if min == -1 || conn.cnt < min {
min = conn.cnt
idx = i
}
}
lc.conns[idx].cnt++
lc.mu.Unlock()
var done bool
return lc.conns[idx].url, func() {
lc.mu.Lock()
if !done {
lc.conns[idx].cnt--
done = true
}
lc.mu.Unlock()
}
}