github.com/gogf/gf/v2@v2.7.4/net/gsel/gsel_selector_random.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/gogf/gf. 6 7 package gsel 8 9 import ( 10 "context" 11 "sync" 12 13 "github.com/gogf/gf/v2/internal/intlog" 14 "github.com/gogf/gf/v2/util/grand" 15 ) 16 17 type selectorRandom struct { 18 mu sync.RWMutex 19 nodes Nodes 20 } 21 22 func NewSelectorRandom() Selector { 23 return &selectorRandom{ 24 nodes: make([]Node, 0), 25 } 26 } 27 28 func (s *selectorRandom) 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 return nil 34 } 35 36 func (s *selectorRandom) Pick(ctx context.Context) (node Node, done DoneFunc, err error) { 37 s.mu.RLock() 38 defer s.mu.RUnlock() 39 if len(s.nodes) == 0 { 40 return nil, nil, nil 41 } 42 node = s.nodes[grand.Intn(len(s.nodes))] 43 intlog.Printf(ctx, `Picked node: %s`, node.Address()) 44 return node, nil, nil 45 }