-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlc.go
50 lines (44 loc) · 1.21 KB
/
lc.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
package goloadbalancer
import (
"sync"
)
type LeastConnectionsEndpoint interface {
Endpoint
ActivateConnections() int
InactiveConnections() int
}
// LeastConnectionsBalance 最小连接数负载均衡
type LeastConnectionsBalance struct {
*BaseLoadBalance
}
// NewLeastConnectionsBalance 创建一个最小连接数负载均衡器
func NewLeastConnectionsBalance(endpoints []Endpoint) LoadBalance {
return &LeastConnectionsBalance{
&BaseLoadBalance{
endpoints: endpoints,
lock: sync.RWMutex{},
},
}
}
func (l *LeastConnectionsBalance) Select(args ...interface{}) (Endpoint, error) {
l.lock.RLock()
defer l.lock.RUnlock()
if len(l.endpoints) == 0 {
return nil, ErrNoEndpoint
}
min := l.endpoints[0].(LeastConnectionsEndpoint)
// Overhead =( Active * 256 + Inactive )/Weight
minOverhead := min.ActivateConnections()*256 + min.InactiveConnections()
for _, endpoint := range l.endpoints {
endpoint := endpoint.(LeastConnectionsEndpoint)
overhead := endpoint.ActivateConnections()*256 + endpoint.InactiveConnections()
if overhead < minOverhead {
min = endpoint
minOverhead = overhead
}
}
return min, nil
}
func (l *LeastConnectionsBalance) Name() string {
return string(LCBalanceType)
}