代码拉取完成,页面将自动刷新
package grpc
import (
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/balancer/base"
"log"
"sync"
)
var no = 0
type WeightBalance struct {
subConns []balancer.SubConn
subWeights []int64
mu sync.Mutex
}
func (b *WeightBalance) Build(info base.PickerBuildInfo) balancer.Picker {
if len(info.ReadySCs) <= 0 {
return base.NewErrPicker(balancer.ErrNoSubConnAvailable)
}
conns := []balancer.SubConn{}
weights := []int64{}
i := 0
for subConn, subInfo := range info.ReadySCs {
i++
conns = append(conns, subConn)
//fmt.Println("subConn", subConn)
//fmt.Println("Attributes", subInfo.Address.Attributes)
//fmt.Println("Addr", subInfo.Address.Addr)
weight := subInfo.Address.Attributes.Value("weight")
w := int64(0)
if weight != nil {
w = weight.(int64)
}
if w <= 0 {
w = 1
}
log.Printf("rpc discovery %d: %s ,%d", i, subInfo.Address.Addr, weight)
weights = append(weights, w)
}
b.mu.Lock()
b.subConns = conns
b.subWeights = weights
no = 0
b.mu.Unlock()
return b
}
func (b *WeightBalance) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
b.mu.Lock()
l := len(b.subWeights)
no++
no = no % l
conn := b.subConns[no]
b.mu.Unlock()
return balancer.PickResult{
SubConn: conn,
}, nil
}
func (b *WeightBalance) Name() string {
return "my_weight_round"
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。