-
Notifications
You must be signed in to change notification settings - Fork 0
/
gsel_selector_weight.go
57 lines (49 loc) · 1.3 KB
/
gsel_selector_weight.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
// 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/internal/intlog"
"github.com/joy12825/gf/net/gsvc"
"github.com/joy12825/gf/util/grand"
)
type selectorWeight struct {
mu sync.RWMutex
nodes Nodes
}
func NewSelectorWeight() Selector {
return &selectorWeight{
nodes: make(Nodes, 0),
}
}
func (s *selectorWeight) Update(ctx context.Context, nodes Nodes) error {
intlog.Printf(ctx, `Update nodes: %s`, nodes.String())
var newNodes []Node
for _, v := range nodes {
node := v
for i := 0; i < s.getWeight(node); i++ {
newNodes = append(newNodes, node)
}
}
s.mu.Lock()
s.nodes = newNodes
s.mu.Unlock()
return nil
}
func (s *selectorWeight) Pick(ctx context.Context) (node Node, done DoneFunc, err error) {
s.mu.RLock()
defer s.mu.RUnlock()
if len(s.nodes) == 0 {
return nil, nil, nil
}
node = s.nodes[grand.Intn(len(s.nodes))]
intlog.Printf(ctx, `Picked node: %s`, node.Address())
return node, nil, nil
}
func (s *selectorWeight) getWeight(node Node) int {
return node.Service().GetMetadata().Get(gsvc.MDWeight).Int()
}