2015-12-09 19:23:16 +00:00
|
|
|
package selector
|
2015-12-09 00:02:45 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"math/rand"
|
|
|
|
"time"
|
2015-12-09 19:23:16 +00:00
|
|
|
|
|
|
|
"github.com/micro/go-micro/registry"
|
2015-12-09 00:02:45 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type randomSelector struct {
|
2015-12-09 19:23:16 +00:00
|
|
|
so Options
|
2015-12-09 00:02:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
rand.Seed(time.Now().Unix())
|
|
|
|
}
|
|
|
|
|
2015-12-09 19:23:16 +00:00
|
|
|
func (r *randomSelector) Select(service string, opts ...SelectOption) (Next, error) {
|
2015-12-09 00:02:45 +00: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 19:23:16 +00:00
|
|
|
var nodes []*registry.Node
|
2015-12-09 00:02:45 +00:00
|
|
|
|
|
|
|
for _, service := range services {
|
|
|
|
for _, node := range service.Nodes {
|
|
|
|
nodes = append(nodes, node)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(nodes) == 0 {
|
|
|
|
return nil, ErrNotFound
|
|
|
|
}
|
|
|
|
|
2015-12-09 19:23:16 +00:00
|
|
|
return func() (*registry.Node, error) {
|
2015-12-09 12:44:38 +00: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 00:02:45 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2015-12-09 19:23:16 +00:00
|
|
|
func (r *randomSelector) Mark(service string, node *registry.Node, err error) {
|
2015-12-09 00:02:45 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *randomSelector) Reset(service string) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *randomSelector) Close() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-12-19 21:56:14 +00:00
|
|
|
func (r *randomSelector) String() string {
|
|
|
|
return "random"
|
|
|
|
}
|
|
|
|
|
2015-12-09 19:23:16 +00:00
|
|
|
func newRandomSelector(opts ...Option) Selector {
|
|
|
|
var sopts Options
|
2015-12-09 00:02:45 +00:00
|
|
|
|
|
|
|
for _, opt := range opts {
|
|
|
|
opt(&sopts)
|
|
|
|
}
|
|
|
|
|
|
|
|
if sopts.Registry == nil {
|
2015-12-09 19:23:16 +00:00
|
|
|
sopts.Registry = registry.DefaultRegistry
|
2015-12-09 00:02:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return &randomSelector{sopts}
|
|
|
|
}
|