1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-18 08:26:38 +02:00
go-micro/selector/strategy.go

57 lines
1.0 KiB
Go
Raw Normal View History

2016-05-03 23:06:19 +02:00
package selector
import (
"math/rand"
"sync"
"time"
2021-10-12 13:55:53 +02:00
"go-micro.dev/v4/registry"
2016-05-03 23:06:19 +02:00
)
func init() {
rand.Seed(time.Now().UnixNano())
}
2022-09-30 16:27:07 +02:00
// Random is a random strategy algorithm for node selection.
2016-05-03 23:06:19 +02:00
func Random(services []*registry.Service) Next {
2019-11-05 19:43:12 +02:00
nodes := make([]*registry.Node, 0, len(services))
2016-05-03 23:06:19 +02:00
for _, service := range services {
nodes = append(nodes, service.Nodes...)
}
return func() (*registry.Node, error) {
if len(nodes) == 0 {
return nil, ErrNoneAvailable
2016-05-03 23:06:19 +02:00
}
i := rand.Int() % len(nodes)
return nodes[i], nil
}
}
2022-09-30 16:27:07 +02:00
// RoundRobin is a roundrobin strategy algorithm for node selection.
2016-05-03 23:06:19 +02:00
func RoundRobin(services []*registry.Service) Next {
nodes := make([]*registry.Node, 0, len(services))
2016-05-03 23:06:19 +02:00
for _, service := range services {
nodes = append(nodes, service.Nodes...)
}
var i = rand.Int()
2016-05-03 23:06:19 +02:00
var mtx sync.Mutex
return func() (*registry.Node, error) {
if len(nodes) == 0 {
return nil, ErrNoneAvailable
2016-05-03 23:06:19 +02:00
}
mtx.Lock()
node := nodes[i%len(nodes)]
i++
mtx.Unlock()
return node, nil
}
}