Files
gf/net/gsel/gsel_selector_random.go

46 lines
1.0 KiB
Go
Raw Permalink Normal View History

2022-01-24 23:33:56 +08:00
// 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"
2022-05-23 15:08:11 +08:00
"github.com/gogf/gf/v2/internal/intlog"
2022-01-24 23:33:56 +08:00
"github.com/gogf/gf/v2/util/grand"
)
type selectorRandom struct {
2022-01-24 23:33:56 +08:00
mu sync.RWMutex
2022-05-23 15:08:11 +08:00
nodes Nodes
2022-01-24 23:33:56 +08:00
}
func NewSelectorRandom() Selector {
return &selectorRandom{
2022-01-24 23:33:56 +08:00
nodes: make([]Node, 0),
}
}
2022-05-23 15:08:11 +08:00
func (s *selectorRandom) 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
2022-01-24 23:33:56 +08:00
return nil
}
func (s *selectorRandom) 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
}
2022-05-23 15:08:11 +08:00
node = s.nodes[grand.Intn(len(s.nodes))]
intlog.Printf(ctx, `Picked node: %s`, node.Address())
return node, nil, nil
2022-01-24 23:33:56 +08:00
}