1 Star 0 Fork 0

CaptialSTeam/ubdframe

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
weight_balance.go 1.31 KB
一键复制 编辑 原始数据 按行查看 历史
Wsage 提交于 2024-12-17 00:59 . !1初始化
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"
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/captials-team/ubdframe.git
git@gitee.com:captials-team/ubdframe.git
captials-team
ubdframe
ubdframe
f282eecfd803

搜索帮助

0d507c66 1850385 C8b1a773 1850385