eastany / eastany.github.com

我的博客
4 stars 3 forks source link

grpc 源码 #59

Open eastany opened 8 years ago

eastany commented 8 years ago

grpc client 源码

clientconn.go

type dialOptions struct {
      codec    Codec
      cp       Compressor
      dc       Decompressor
      picker   Picker
      block    bool
      insecure bool
      copts    transport.ConnectOptions
}

codec - 编解码接口

cp/dc - 压缩/解压缩接口

picker - 连接选择器,不建议自己实现

block - 阻塞

insecure - 启用xls

copts - 连接设置(包括UA,Dial函数,连接超时,认证设置)

主要的函数如下:

Dial函数:

type ClientConn struct {
    target    string
    authority string
    dopts     dialOptions
}

func Dial(target string, opts ...DialOption) (*ClientConn, error) {
    cc := &ClientConn{
        target: target,
    }
    for _, opt := range opts {
        opt(&cc.dopts) // 设置连接
    }
    if cc.dopts.codec == nil {
        // 设置默认编解码
        cc.dopts.codec = protoCodec{}
    }
    if cc.dopts.picker == nil {
       // 设置默认picker
        cc.dopts.picker = &unicastPicker{
            target: target,
        }
    }
    if err := cc.dopts.picker.Init(cc); err != nil {
        return nil, err
    }
    colonPos := strings.LastIndex(target, ":")
    if colonPos == -1 {
        colonPos = len(target)
    }
    cc.authority = target[:colonPos]
    return cc, nil
}