-
Notifications
You must be signed in to change notification settings - Fork 0
/
roundrobin.go
62 lines (53 loc) · 1.35 KB
/
roundrobin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Package roundrobin implements a roundrobin call strategy
package roundrobin
import (
"sync"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/selector"
"context"
)
type roundrobin struct {
sync.Mutex
rr map[string]int
client.Client
}
func (s *roundrobin) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
nOpts := append(opts, client.WithSelectOption(
// create a selector strategy
selector.WithStrategy(func(services []*registry.Service) selector.Next {
// flatten
var nodes []*registry.Node
for _, service := range services {
nodes = append(nodes, service.Nodes...)
}
// create the next func that always returns our node
return func() (*registry.Node, error) {
if len(nodes) == 0 {
return nil, selector.ErrNoneAvailable
}
s.Lock()
// get counter
rr := s.rr[req.Service()]
// get node
node := nodes[rr%len(nodes)]
// increment
rr++
// save
s.rr[req.Service()] = rr
s.Unlock()
return node, nil
}
}),
))
return s.Client.Call(ctx, req, rsp, nOpts...)
}
// NewClientWrapper is a wrapper which roundrobins requests
func NewClientWrapper() client.Wrapper {
return func(c client.Client) client.Client {
return &roundrobin{
rr: make(map[string]int),
Client: c,
}
}
}