2020-06-30 16:54:38 +03:00
|
|
|
package roundrobin
|
|
|
|
|
|
|
|
import (
|
2020-11-30 22:48:00 +03:00
|
|
|
"math/rand"
|
|
|
|
|
2020-08-19 17:47:17 +03:00
|
|
|
"github.com/unistack-org/micro/v3/selector"
|
2020-06-30 16:54:38 +03:00
|
|
|
)
|
|
|
|
|
2020-08-25 15:41:48 +03:00
|
|
|
// NewSelector returns an initialised round robin selector
|
2020-06-30 16:54:38 +03:00
|
|
|
func NewSelector(opts ...selector.Option) selector.Selector {
|
2020-08-18 00:44:45 +03:00
|
|
|
return new(roundrobin)
|
2020-06-30 16:54:38 +03:00
|
|
|
}
|
|
|
|
|
2020-08-18 00:44:45 +03:00
|
|
|
type roundrobin struct{}
|
2020-07-02 18:09:48 +03:00
|
|
|
|
2020-08-25 15:41:48 +03:00
|
|
|
// Select return routes based on algo
|
2020-08-18 00:44:45 +03:00
|
|
|
func (r *roundrobin) Select(routes []string, opts ...selector.SelectOption) (selector.Next, error) {
|
2020-06-30 16:54:38 +03:00
|
|
|
if len(routes) == 0 {
|
|
|
|
return nil, selector.ErrNoneAvailable
|
|
|
|
}
|
|
|
|
|
2020-11-30 22:48:00 +03:00
|
|
|
i := rand.Intn(len(routes))
|
2020-06-30 16:54:38 +03:00
|
|
|
|
2020-08-18 00:44:45 +03:00
|
|
|
return func() string {
|
|
|
|
route := routes[i%len(routes)]
|
|
|
|
// increment
|
|
|
|
i++
|
|
|
|
return route
|
|
|
|
}, nil
|
2020-06-30 16:54:38 +03:00
|
|
|
}
|
|
|
|
|
2020-08-18 00:44:45 +03:00
|
|
|
func (r *roundrobin) Record(addr string, err error) error { return nil }
|
2020-06-30 16:54:38 +03:00
|
|
|
|
2020-08-18 00:44:45 +03:00
|
|
|
func (r *roundrobin) Reset() error { return nil }
|
2020-06-30 16:54:38 +03:00
|
|
|
|
|
|
|
func (r *roundrobin) String() string {
|
|
|
|
return "roundrobin"
|
|
|
|
}
|