2022-01-27 15:15:55 +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-27 15:15:55 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
const SelectorRoundRobin = "BalancerRoundRobin"
|
|
|
|
|
|
|
|
type selectorRoundRobin struct {
|
|
|
|
mu sync.RWMutex
|
2022-05-23 15:08:11 +08:00
|
|
|
nodes Nodes
|
2022-01-27 15:15:55 +08:00
|
|
|
next int
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSelectorRoundRobin() Selector {
|
|
|
|
return &selectorRoundRobin{
|
2022-05-23 15:08:11 +08:00
|
|
|
nodes: make(Nodes, 0),
|
2022-01-27 15:15:55 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-23 15:08:11 +08:00
|
|
|
func (s *selectorRoundRobin) Update(ctx context.Context, nodes Nodes) error {
|
|
|
|
intlog.Printf(ctx, `Update nodes: %s`, nodes.String())
|
2022-01-27 15:15:55 +08:00
|
|
|
s.mu.Lock()
|
|
|
|
s.nodes = nodes
|
|
|
|
s.mu.Unlock()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *selectorRoundRobin) Pick(ctx context.Context) (node Node, done DoneFunc, err error) {
|
|
|
|
s.mu.RLock()
|
|
|
|
defer s.mu.RUnlock()
|
|
|
|
node = s.nodes[s.next]
|
|
|
|
s.next = (s.next + 1) % len(s.nodes)
|
2022-05-23 15:08:11 +08:00
|
|
|
intlog.Printf(ctx, `Picked node: %s`, node.Address())
|
2022-01-27 15:15:55 +08:00
|
|
|
return
|
|
|
|
}
|