micro/selector/random_selector.go

105 lines
1.7 KiB
Go
Raw Normal View History

2015-12-09 22:23:16 +03:00
package selector
2015-12-09 03:02:45 +03:00
import (
"math/rand"
"time"
2015-12-09 22:23:16 +03:00
"github.com/micro/go-micro/registry"
2015-12-09 03:02:45 +03:00
)
type randomSelector struct {
2015-12-09 22:23:16 +03:00
so Options
2015-12-09 03:02:45 +03:00
}
func init() {
rand.Seed(time.Now().Unix())
}
2016-01-05 02:07:56 +03:00
func (r *randomSelector) Init(opts ...Option) error {
for _, o := range opts {
o(&r.so)
}
return nil
}
func (r *randomSelector) Options() Options {
return r.so
}
2015-12-09 22:23:16 +03:00
func (r *randomSelector) Select(service string, opts ...SelectOption) (Next, error) {
2015-12-09 03:02:45 +03:00
var sopts SelectOptions
for _, opt := range opts {
opt(&sopts)
}
// get the service
services, err := r.so.Registry.GetService(service)
if err != nil {
return nil, err
}
// apply the filters
for _, filter := range sopts.Filters {
services = filter(services)
}
// if there's nothing left, return
if len(services) == 0 {
return nil, ErrNotFound
}
2015-12-09 22:23:16 +03:00
var nodes []*registry.Node
2015-12-09 03:02:45 +03:00
for _, service := range services {
for _, node := range service.Nodes {
nodes = append(nodes, node)
}
}
if len(nodes) == 0 {
return nil, ErrNotFound
}
2015-12-09 22:23:16 +03:00
return func() (*registry.Node, error) {
2015-12-09 15:44:38 +03:00
i := rand.Int()
j := i % len(services)
if len(services[j].Nodes) == 0 {
return nil, ErrNotFound
}
k := i % len(services[j].Nodes)
return services[j].Nodes[k], nil
2015-12-09 03:02:45 +03:00
}, nil
}
2015-12-09 22:23:16 +03:00
func (r *randomSelector) Mark(service string, node *registry.Node, err error) {
2015-12-09 03:02:45 +03:00
return
}
func (r *randomSelector) Reset(service string) {
return
}
func (r *randomSelector) Close() error {
return nil
}
2015-12-20 00:56:14 +03:00
func (r *randomSelector) String() string {
return "random"
}
2015-12-09 22:23:16 +03:00
func newRandomSelector(opts ...Option) Selector {
var sopts Options
2015-12-09 03:02:45 +03:00
for _, opt := range opts {
opt(&sopts)
}
if sopts.Registry == nil {
2015-12-09 22:23:16 +03:00
sopts.Registry = registry.DefaultRegistry
2015-12-09 03:02:45 +03:00
}
return &randomSelector{sopts}
}