-
Notifications
You must be signed in to change notification settings - Fork 0
/
gsel_selector_least_connection.go
71 lines (63 loc) · 1.64 KB
/
gsel_selector_least_connection.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
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/joy12825/gf.
package gsel
import (
"context"
"sync"
"github.com/joy12825/gf/container/gtype"
"github.com/joy12825/gf/internal/intlog"
)
type selectorLeastConnection struct {
mu sync.RWMutex
nodes []*leastConnectionNode
}
type leastConnectionNode struct {
Node
inflight *gtype.Int
}
func NewSelectorLeastConnection() Selector {
return &selectorLeastConnection{
nodes: make([]*leastConnectionNode, 0),
}
}
func (s *selectorLeastConnection) Update(ctx context.Context, nodes Nodes) error {
intlog.Printf(ctx, `Update nodes: %s`, nodes.String())
var newNodes []*leastConnectionNode
for _, v := range nodes {
node := v
newNodes = append(newNodes, &leastConnectionNode{
Node: node,
inflight: gtype.NewInt(),
})
}
s.mu.Lock()
defer s.mu.Unlock()
s.nodes = newNodes
return nil
}
func (s *selectorLeastConnection) Pick(ctx context.Context) (node Node, done DoneFunc, err error) {
s.mu.RLock()
defer s.mu.RUnlock()
var pickedNode *leastConnectionNode
if len(s.nodes) == 1 {
pickedNode = s.nodes[0]
} else {
for _, v := range s.nodes {
if pickedNode == nil {
pickedNode = v
} else if v.inflight.Val() < pickedNode.inflight.Val() {
pickedNode = v
}
}
}
pickedNode.inflight.Add(1)
done = func(ctx context.Context, di DoneInfo) {
pickedNode.inflight.Add(-1)
}
node = pickedNode.Node
intlog.Printf(ctx, `Picked node: %s`, node.Address())
return node, done, nil
}