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.
go-zero/rpcx/internal/balancer/roundrobin/roundrobin.go

65 lines
1.2 KiB
Go

package roundrobin
4 years ago
import (
4 years ago
"context"
"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
)
const Name = "zero_rr"
4 years ago
func init() {
balancer.Register(newRoundRobinBuilder())
4 years ago
}
type roundRobinPickerBuilder struct {
}
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) {
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
}