You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
65 lines
1.2 KiB
Go
65 lines
1.2 KiB
Go
4 years ago
|
package roundrobin
|
||
4 years ago
|
|
||
|
import (
|
||
4 years ago
|
"context"
|
||
4 years ago
|
"fmt"
|
||
4 years ago
|
"math/rand"
|
||
|
"sync"
|
||
|
"time"
|
||
4 years ago
|
|
||
4 years ago
|
"google.golang.org/grpc/balancer"
|
||
|
"google.golang.org/grpc/balancer/base"
|
||
4 years ago
|
"google.golang.org/grpc/resolver"
|
||
4 years ago
|
)
|
||
|
|
||
4 years ago
|
const Name = "zero_rr"
|
||
4 years ago
|
|
||
|
func init() {
|
||
4 years ago
|
balancer.Register(newRoundRobinBuilder())
|
||
4 years ago
|
}
|
||
|
|
||
|
type roundRobinPickerBuilder struct {
|
||
|
}
|
||
|
|
||
4 years ago
|
func newRoundRobinBuilder() balancer.Builder {
|
||
4 years ago
|
return base.NewBalancerBuilder(Name, new(roundRobinPickerBuilder))
|
||
|
}
|
||
|
|
||
4 years ago
|
func (b *roundRobinPickerBuilder) Build(readySCs map[resolver.Address]balancer.SubConn) balancer.Picker {
|
||
4 years ago
|
rand.Seed(time.Now().UnixNano())
|
||
|
picker := &roundRobinPicker{
|
||
|
index: rand.Int(),
|
||
|
}
|
||
|
|
||
|
for addr, conn := range readySCs {
|
||
|
picker.conns = append(picker.conns, &subConn{
|
||
|
addr: addr,
|
||
|
conn: conn,
|
||
|
})
|
||
|
}
|
||
|
|
||
|
return picker
|
||
4 years ago
|
}
|
||
|
|
||
|
type roundRobinPicker struct {
|
||
4 years ago
|
conns []*subConn
|
||
|
index int
|
||
|
lock sync.Mutex
|
||
4 years ago
|
}
|
||
|
|
||
|
func (p *roundRobinPicker) Pick(ctx context.Context, info balancer.PickInfo) (
|
||
|
conn balancer.SubConn, done func(balancer.DoneInfo), err error) {
|
||
4 years ago
|
fmt.Println(p.conns)
|
||
4 years ago
|
p.lock.Lock()
|
||
|
defer p.lock.Unlock()
|
||
|
|
||
|
p.index = (p.index + 1) % len(p.conns)
|
||
|
return p.conns[p.index].conn, func(info balancer.DoneInfo) {
|
||
|
}, nil
|
||
|
}
|
||
|
|
||
|
type subConn struct {
|
||
|
addr resolver.Address
|
||
|
conn balancer.SubConn
|
||
4 years ago
|
}
|