github.com/wangyougui/gf/v2@v2.6.5/net/gsel/gsel_selector_round_robin.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package gsel 8 9 import ( 10 "context" 11 "sync" 12 13 "github.com/wangyougui/gf/v2/internal/intlog" 14 ) 15 16 type selectorRoundRobin struct { 17 mu sync.Mutex 18 nodes Nodes 19 next int 20 } 21 22 func NewSelectorRoundRobin() Selector { 23 return &selectorRoundRobin{ 24 nodes: make(Nodes, 0), 25 } 26 } 27 28 func (s *selectorRoundRobin) Update(ctx context.Context, nodes Nodes) error { 29 intlog.Printf(ctx, `Update nodes: %s`, nodes.String()) 30 s.mu.Lock() 31 defer s.mu.Unlock() 32 s.nodes = nodes 33 s.next = 0 34 return nil 35 } 36 37 func (s *selectorRoundRobin) Pick(ctx context.Context) (node Node, done DoneFunc, err error) { 38 s.mu.Lock() 39 defer s.mu.Unlock() 40 if len(s.nodes) == 0 { 41 return 42 } 43 node = s.nodes[s.next] 44 s.next = (s.next + 1) % len(s.nodes) 45 intlog.Printf(ctx, `Picked node: %s`, node.Address()) 46 return 47 }