gRPC-go自定义负载均衡策略

前言

grpc默认支持两种负载均衡算法pick_first 和 round_robin

轮询法round_robin不能满足因服务器配置不同而承担不同负载量,这篇文章将介绍如何实现自定义负载均衡策略--加权随机。

加权随机法可以根据服务器的处理能力而分配不同的权重,从而实现处理能力高的服务器可承担更多的请求,处理能力低的服务器少承担请求。

上一篇我们实现resolverBuilder接口,用来解析服务器地址,而负载均衡算法就是在这个接口基础上筛选出一个地址,这个过程是在客户端发送请求的时候进行。

以下示例基于grpc v1.26.0版本,更高的版本不兼容etcd,不方便测试,而接口名或者参数也会不同,不过原理是相似的

自定义负载均衡策略

使用自定义的负载均衡策略主要实现V2PickerBuilderV2Picker这两个接口

type V2PickerBuilder interface {
    Build(info PickerBuildInfo) balancer.V2Picker
}

Build方法:返回一个V2选择器,将用于gRPC选择子连接。

type V2Picker interface {
    Pick(info PickInfo) (PickResult, error)
}

Pick方法:子连接选择,具体的算法在这个方法内实现

完整代码:

package rpc

import (
    "google.golang.org/grpc/balancer"
    "google.golang.org/grpc/balancer/base"
    "google.golang.org/grpc/grpclog"
    "math/rand"
    "sync"
)

const WEIGHT_LB_NAME =  "weight"

func init() {
    balancer.Register(
        base.NewBalancerBuilderV2(WEIGHT_LB_NAME,&LocalBuilder{},base.Config{HealthCheck: false}))
}

type LocalBuilder struct {

}

func (*LocalBuilder) Build(info base.PickerBuildInfo) balancer.V2Picker {
    if len(info.ReadySCs) == 0 {
        return base.NewErrPickerV2(balancer.ErrNoSubConnAvailable)
    }
    var scs []balancer.SubConn
    for subConn,addr := range info.ReadySCs {
        weight := addr.Address.Attributes.Value("weight").(int)
        if weight <= 0 {
            weight = 1
        }
        for i := 0; i < weight; i++ {
            scs = append(scs, subConn)
        }
    }
    return &localPick{
        subConn: scs,
    }
}

type localPick struct {
    subConn []balancer.SubConn
    mu sync.Mutex
}

func  (l *localPick)Pick(info balancer.PickInfo) (r balancer.PickResult, err error){
    l.mu.Lock()
    index := rand.Intn(len(l.subConn))
    r.SubConn = l.subConn[index]
    l.mu.Lock()
    return r,nil
}

结合示例再看一下Build(info PickerBuildInfo) balancer.V2Picker这个方法的作用:

这个函数的返回值就是我们还要实现的第二个接口,所以这里主要看一下参数

type PickerBuildInfo struct {
    // ReadySCs is a map from all ready SubConns to the Addresses used to
    // create them.
    ReadySCs map[balancer.SubConn]
}

type SubConnInfo struct {
    Address resolver.Address // the address used to create this SubConn
}

ReadySCs:是所有可用的子连接
balancer.SubConn:是一个子连接的结构,这里我们不用关心这个值,在pick里面直接返回就可以了。
SubConnInfo:里面是一个Address的结构

type Address struct {
    Addr string
    ServerName string

    // Attributes contains arbitrary data about this address intended for
    // consumption by the load balancing policy.
    Attributes *attributes.Attributes  
    Type AddressType
    Metadata interface{}
}
...
...
type Attributes struct {
    m map[interface{}]interface{}
}

这个Address就是上一篇中resolverBuilder中设置的值,所以这两个功能是有联系的,Attributes的m是一个map,刚刚好保存我们需要的权重weight

结下来就是Pick方法
Pick(info balancer.PickInfo) (r balancer.PickResult, err error)

type PickInfo struct {
    // FullMethodName is the method name that NewClientStream() is called
    // with. The canonical format is /service/Method.
    FullMethodName string    //eg : /User/GetInfo
    // Ctx is the RPC's context, and may contain relevant RPC-level information
    // like the outgoing header metadata.
    Ctx context.Context
}

type PickResult struct {
    SubConn SubConn
    Done func(DoneInfo)
}

FullMethodName:对应XXXpb.go中生成的FullMethod: "/Memo/GetMemo",
Ctx: 如注释所说,包含metadata
PickResult: 返回的子连接
Done:rpc完成之后调用Done

使用新建的策略

func main()  {
    grpc.UseCompressor(gzip.Name)
    conn, err := grpc.Dial(
        fmt.Sprintf("%s:///%s", "game", baseService),
        //grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, roundrobin.Name)),
        grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, rpc.WEIGHT_LB_NAME)),
        grpc.WithInsecure(),
    )  
      ...
}

你可能感兴趣的:(gRPC-go自定义负载均衡策略)