-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
gsel_selector_round_robin.go
47 lines (40 loc) · 1 KB
/
gsel_selector_round_robin.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
// 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/gogf/gf.
package gsel
import (
"context"
"sync"
"github.com/gogf/gf/v2/internal/intlog"
)
type selectorRoundRobin struct {
mu sync.Mutex
nodes Nodes
next int
}
func NewSelectorRoundRobin() Selector {
return &selectorRoundRobin{
nodes: make(Nodes, 0),
}
}
func (s *selectorRoundRobin) Update(ctx context.Context, nodes Nodes) error {
intlog.Printf(ctx, `Update nodes: %s`, nodes.String())
s.mu.Lock()
defer s.mu.Unlock()
s.nodes = nodes
s.next = 0
return nil
}
func (s *selectorRoundRobin) Pick(ctx context.Context) (node Node, done DoneFunc, err error) {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.nodes) == 0 {
return
}
node = s.nodes[s.next]
s.next = (s.next + 1) % len(s.nodes)
intlog.Printf(ctx, `Picked node: %s`, node.Address())
return
}