gRPC

 概述

gRPC 一开始由 google 开发,是一款语言中立、平台中立、开源的远程过程调用(RPC)系统。

在 gRPC 里客户端应用可以像调用本地对象一样直接调用另一台不同的机器上服务端应用的方法,使得您能够更容易地创建分布式应用和服务。与许多 RPC 系统类似,gRPC 也是基于以下理念:定义一个服务,指定其能够被远程调用的方法(包含参数和返回类型)。在服务端实现这个接口,并运行一个 gRPC 服务器来处理客户端调用。在客户端拥有一个存根能够像服务端一样的方法。

  特性

  • 基于HTTP/2 
    HTTP/2 提供了连接多路复用、双向流、服务器推送、请求优先级、首部压缩等机制。可以节省带宽、降低TCP链接次数、节省CPU,帮助移动设备延长电池寿命等。gRPC 的协议设计上使用了HTTP2 现有的语义,请求和响应的数据使用HTTP Body 发送,其他的控制信息则用Header 表示。
  • IDL使用ProtoBuf 
    gRPC使用ProtoBuf来定义服务,ProtoBuf是由Google开发的一种数据序列化协议(类似于XML、JSON、hessian)。ProtoBuf能够将数据进行序列化,并广泛应用在数据存储、通信协议等方面。压缩和传输效率高,语法简单,表达力强。
  • 多语言支持(C, C++, Python, PHP, Nodejs, C#, Objective-C、Golang、Java)
    gRPC支持多种语言,并能够基于语言自动生成客户端和服务端功能库。目前已提供了C版本grpc、Java版本grpc-java 和 Go版本grpc-go,其它语言的版本正在积极开发中,其中,grpc支持C、C++、Node.js、Python、Ruby、Objective-C、PHP和C#等语言,grpc-java已经支持Android开发。

gRPC已经应用在Google的云服务和对外提供的API中,其主要应用场景如下:
- 低延迟、高扩展性、分布式的系统
- 同云服务器进行通信的移动应用客户端
- 设计语言独立、高效、精确的新协议
- 便于各方面扩展的分层设计,如认证、负载均衡、日志记录、监控等

  HTTP2.0 特性

HTTP/2,也就是超文本传输协议第2版,不论是1还是2,HTTP的基本语义是不变的,比如方法语义(GET/PUST/PUT/DELETE),状态码(200/404/500等),Range Request,Cacheing,Authentication、URL路径, 不同的主要是下面几点:

多路复用 (Multiplexing)

在 HTTP/1.1 协议中 「浏览器客户端在同一时间,针对同一域名下的请求有一定数量限制。超过限制数目的请求会被阻塞」。

HTTP/2 的多路复用(Multiplexing) 则允许同时通过单一的 HTTP/2 连接发起多重的请求-响应消息。
因此 HTTP/2 可以很容易的去实现多流并行而不用依赖建立多个 TCP 连接,HTTP/2 把 HTTP 协议通信的基本单位缩小为一个一个的帧,这些帧对应着逻辑流中的消息。并行地在同一个 TCP 连接上双向交换消息。

二进制帧

HTTP/2 传输的数据是二进制的。相比 HTTP/1.1 的纯文本数据,二进制数据一个显而易见的好处是:更小的传输体积。这就意味着更低的负载。二进制的帧也更易于解析而且不易出错,纯文本帧在解析的时候还要考虑处理空格、大小写、空行和换行等问题,而二进制帧就不存在这个问题。

首部压缩(Header Compression)

HTTP是无状态协议。简而言之,这意味着每个请求必须要携带服务器需要的所有细节,而不是让服务器保存住之前请求的元数据。因为http2没有改变这个范式,所以它也需要这样(携带所有细节),因此 HTTP 请求的头部需要包含用于标识身份的数据比如 cookies,而这些数据的量也在随着时间增长。每一个请求的头部都包含这些大量的重复数据,无疑是一种很大的负担。对请求头部进行压缩,将会大大减轻这种负担,尤其对移动端来说,性能提高非常明显。

HTTP/2 使用的压缩方式是 HPACK。 http://http2.github.io/http2-spec/compression.html

HTTP2.0在客户端和服务器端使用“首部表”来跟踪和存储之前发送的键-值对,对于相同的数据,不再通过每次请求和响应发送;通信期间几乎不会改变的通用键-值对(用户代理、可接受的媒体类型,等等)只需发送一次。

事实上,如果请求中不包含首部(例如对同一资源的轮询请求),那么首部开销就是零字节。此时所有首部都自动使用之前请求发送的首部。

如果首部发生变化了,那么只需要发送变化了数据在Headers帧里面,新增或修改的首部帧会被追加到“首部表”。首部表在 HTTP2.0的连接存续期内始终存在,由客户端和服务器共同渐进地更新。

服务端推送(Server Push)

HTTP/2 的服务器推送所作的工作就是,服务器在收到客户端对某个资源的请求时,会判断客户端十有八九还要请求其他的什么资源,然后一同把这些资源都发送给客户端,即便客户端还没有明确表示它需要这些资源。

客户端可以选择把额外的资源放入缓存中(所以这个特点也叫 Cache push),也可以选择发送一个 RST_STREAM frame 拒绝任何它不想要的资源。

主动重置链接

Length的HTTP消息被送出之后,我们就很难中断它了。当然,通常我们可以断开整个TCP链接(但也不总是可以这样),但这样导致的代价就是需要重新通过三次握手建立一个新的TCP连接。

HTTP/2 引入了一个 RST_STREAM frame 来让客户端在已有的连接中发送重置请求,从而中断或者放弃响应。当浏览器进行页面跳转或者用户取消下载时,它可以防止建立新连接,避免浪费所有带宽。

  与其他rpc比较

与thrift,dubbo,motan等比较

MotanDubboxthriftgRPCrpcx开发语言JavaJava跨语言跨语言go分布式服务治理YY可以配合zookeeper, Eureka等实现可以配合etcd(go),zookeeper,consul等实现自带服务注册中心,也支持zookerper,etcd等发现方式底层协议motan协议,使用tcp长连接Dubbo 协议、 Rmi 协议、 Hessian 协议、 HTTP 协议、 WebService 协议、Dubbo Thrift 协议、Memcached 协议tpc/http/framehttp2tcp长链接消息序列化hessian2,jsonhessian2,json,resr,kyro,FST等,可扩展protobuf等thriftprotobufGob、Json、MessagePack、gencode、ProtoBuf等跨语言编程N(支持php client和c server)NYYN负载均衡ActiveWeight 、Random 、 RoundRobin 、LocalFirst 、 Consistent 、ConfigurableWeightRandom 、RoundRobin 、ConsistentHash 、 LeastActiveHaproxy, zookerper+客户端负载均衡等方案负载均衡软件HaProxy等支持随机请求、轮询、低并发优先、一致性 Hash等容错Failover 失效切换、Failfast 快速失败Failover 、 Failfast 、Failsafe 、 Failback 、 Forking、 BroadcastFailover具有 Failover 失效切换的容错策略失败重试(Failover)、快速失败(Failfast)注册中心consulzookeeperzookeeperetcd,zookeeper,consulzookerper,etcd性能★★★★★★★★ 比grpc快2-5倍★★★ 比dubbox,motan快★★★★★ 比thrift快1-1.5倍侧重优势服务管理服务管理跨语言,性能++跨语言,性能性能++,服务治理客户端异步调用方案  
  • 使用thrift IDL “oneway” 关键字(无返回结果),+callback
    tcp异步请求
    - thrift IDL参数不支持函数或服务
stream传输,双向通信 服务端异步处理  1、TNonblockingServer(java/c++,php); THsHaServer(java/c++); TThreadpoolServer(java/c++); TThreadSelectorServer(java/c++)
2、结合消息队列或中间件
3、swoole/goroutine等多任务支持同上,使用stream传输。Stream对象在传输过程中会被当做集合,用Iterator来遍历处理

grpc vs thrift:

使用gRPC的公司或项目:

Google
Mochi中国
阿里OTS
腾讯部分部门
Tensorflow项目中使用了grpc
CoreOS — Production API for etcd v3 is entirely gRPC. etcd v3的接口全部使用grpc
Square — replacement for all of their internal RPC. one of the very first adopters and contributors to gRPC.
ngrok — all 20+ internal services communicate via gRPC 一个内网转发产品
Netflix
Yik Yak
VSCO
Cockroach

使用Thrift的公司或项目:

Facebook
雪球
饿了么
今日头条 
evernote
友盟
小米
美团
Quora
Twitter
Pinterest
Foursquare
Maxeler Technologies

gRPC优缺点:

优点:

protobuf二进制消息,性能好/效率高(空间和时间效率都很不错)
proto文件生成目标代码,简单易用
序列化反序列化直接对应程序中的数据类,不需要解析后在进行映射(XML,JSON都是这种方式)
支持向前兼容(新加字段采用默认值)和向后兼容(忽略新加字段),简化升级
支持多种语言(可以把proto文件看做IDL文件)
Netty等一些框架集成

缺点:

1)GRPC尚未提供连接池,需要自行实现
2)尚未提供“服务发现”、“负载均衡”机制
3)因为基于HTTP2,绝大部多数HTTP Server、Nginx都尚不支持,即Nginx不能将GRPC请求作为HTTP请求来负载均衡,而是作为普通的TCP请求。(nginx1.9版本已支持)
4) Protobuf二进制可读性差(貌似提供了Text_Fromat功能)
默认不具备动态特性(可以通过动态定义生成消息类型或者动态编译支持)

grpc坑:

来自https://news.ycombinator.com/item?id=12345223的网友:
http2只允许单个链接传输10亿流数据。原因在于:
htt2使用31位整形标示流,服务端使用奇数,客户端使用偶数,所以总共10亿可用。

  1.  
    HTTP/2.0 uses an unsigned 31-bit integer to identity individual streams over a connection.
  2.  
    Server-initiated streams must use even identifiers.
  3.  
    Client-initiated streams must use odd identifiers.

解决思路:超过一定数量的流,需要重启链接。

  gRPC通信方式

gRPC有四种通信方式:
1、 Simple RPC
简单rpc
这就是一般的rpc调用,一个请求对象对应一个返回对象
proto语法:

rpc simpleHello(Person) returns (Result) {}

2、 Server-side streaming RPC
服务端流式rpc
一个请求对象,服务端可以传回多个结果对象
proto语法

rpc serverStreamHello(Person) returns (stream Result) {}

3、 Client-side streaming RPC
客户端流式rpc
客户端传入多个请求对象,服务端返回一个响应结果
proto语法

rpc clientStreamHello(stream Person) returns (Result) {}

4、 Bidirectional streaming RPC
双向流式rpc
结合客户端流式rpc和服务端流式rpc,可以传入多个对象,返回多个响应对象
proto语法

rpc biStreamHello(stream Person) returns (stream Result) {}

  服务定义及ProtoBuf

gRPC使用ProtoBuf定义服务, 我们可以一次性的在一个 .proto 文件中定义服务并使用任何支持它的语言去实现客户端和服务器,反过来,它们可以在各种环境中,从云服务器到你自己的平板电脑—— gRPC 帮你解决了不同语言及环境间通信的复杂性。使用 protocol buffers 还能获得其他好处,包括高效的序列号,简单的 IDL 以及容易进行接口更新。

protoc编译工具

protoc工具可在https://github.com/google/protobuf/releases 下载到源码。
linux下安装

protobuf语法

1、syntax = “proto3”;
文件的第一行指定了你使用的是proto3的语法:如果你不指定,protocol buffer 编译器就会认为你使用的是proto2的语法。这个语句必须出现在.proto文件的非空非注释的第一行。
2、message SearchRequest {……}
message 定义实体,c/c++/go中的结构体,php中类
3、基本数据类型

4、注释符号: 双斜线,如://xxxxxxxxxxxxxxxxxxx
5、字段唯一数字标识(用于在二进制格式中识别各个字段,上线后不宜再变动):Tags
1到15使用一个字节来编码,包括标识数字和字段类型(你可以在Protocol Buffer 编码中查看更多详细);16到2047占用两个字节。因此定义proto文件时应该保留1到15,用作出现最频繁的消息类型的标识。记得为将来会继续增加并可能频繁出现的元素留一点儿标识区间,也就是说,不要一下子把1—15全部用完,为将来留一点儿。
标识数字的合法范围:最小是1,最大是 229 - 1,或者536,870,911。
另外,不能使用19000 到 19999之间的数字(FieldDescriptor::kFirstReservedNumber through FieldDescriptor::kLastReservedNumber),因为它们被Protocol Buffers保留使用
6、字段修饰符:
required:值不可为空
optional:可选字段
singular:符合语法规则的消息包含零个或者一个这样的字段(最多一个)
repeated:一个字段在合法的消息中可以重复出现一定次数(包括零次)。重复出现的值的次序将被保留。在proto3中,重复出现的值类型字段默认采用压缩编码。你可以在这里找到更多关于压缩编码的东西: Protocol Buffer Encoding。
默认值: optional PhoneType type = 2 [default = HOME];
proto3中,省略required,optional,singular,由protoc自动选择。
7、代理类生成
1)、C++, 每一个.proto 文件可以生成一个 .h 文件和一个 .cc 文件
2)、Java, 每一个.proto文件可以生成一个 .java 文件
3)、Python, 每一个.proto文件生成一个模块,其中为每一个消息类型生成一个静态的描述器,在运行时,和一个metaclass一起使用来创建必要的Python数据访问类
4)、Go, 每一个.proto生成一个 .pb.go 文件
5)、Ruby, 每一个.proto生成一个 .rb 文件
6)、Objective-C, 每一个.proto 文件可以生成一个 pbobjc.h 和一个pbobjc.m 文件
7)、C#, 每一个.proto文件可以生成一个.cs文件.
8)、php, 每一个message消息体生成一个.php类文件,并在GPBMetadata目录生成一个对应包名的.php类文件,用于保存.proto的二进制元数据。
8、字段默认值
- strings, 默认值是空字符串(empty string)
- bytes, 默认值是空bytes(empty bytes)
- bools, 默认值是false
- numeric, 默认值是0
- enums, 默认值是第一个枚举值(value必须为0)
- message fields, the field is not set. Its exact value is langauge-dependent. See the generated code guide for details.
- repeated fields,默认值为empty,通常是一个空list
9、枚举

  1.  
    // 枚举类型,必须从0开始,序号可跨越。同一包下不能重名,所以加前缀来区别
  2.  
    enum WshExportInstStatus {
  3.  
    INST_INITED = 0;
  4.  
    INST_RUNNING = 1;
  5.  
    INST_FINISH = 2;
  6.  
    INST_FAILED = 3;
  7.  
    }

10、Maps字段类型

map<key_type, value_type> map_field = N;

其中key_type可以是任意Integer或者string类型(所以,除了floating和bytes的任意标量类型都是可以的)value_type可以是任意类型。
例如,如果你希望创建一个project的映射,每个Projecct使用一个string作为key,你可以像下面这样定义:

map<string, Project> projects = 3;
  • Map的字段可以是repeated。
  • 序列化后的顺序和map迭代器的顺序是不确定的,所以你不要期望以固定顺序处理Map
  • 当为.proto文件产生生成文本格式的时候,map会按照key 的顺序排序,数值化的key会按照数值排序。
  • 从序列化中解析或者融合时,如果有重复的key则后一个key不会被使用,当从文本格式中解析map时,如果存在重复的key。

11、默认值
字符串类型默认为空字符串
字节类型默认为空字节
布尔类型默认false
数值类型默认为0值
enums类型默认为第一个定义的枚举值,必须是0

12、服务
服务使用service{}包起来,每个方法使用rpc起一行申明,一个方法包含一个请求消息体和一个返回消息体

  1.  
    service HelloService {
  2.  
    rpc SayHello (HelloRequest) returns (HelloResponse);
  3.  
    }
  4.  
    message HelloRequest {
  5.  
    string greeting = 1;
  6.  
    }
  7.  
  8.  
    message HelloResponse {
  9.  
    string reply = 1;
  10.  
    }

更多protobuf参考(google) 
更多protobuf参考(csdn)

  golang中使用gRPC

前期准备

  1.  
    go get -u “google.golang.org/grpc”
  2.  
    go get -u “google.golang.org/grpc/reflection”
  • 1
  • 2

例如我定义的文件exporttask.proto:

  1.  
    // 微生活导出服务
  2.  
    // 导出功能接口
  3.  
    /
  4.  
    1、 创建任务模板
  5.  
    2、 查询、列出任务模板
  6.  
    3、 删除任务模板
  7.  
    4、 添加导出任务实例
  8.  
    5、 查询任务状态
  9.  
    /
  10.  
    syntax = “proto3”;
  11.  
  12.  
    // java 语法特别选项
  13.  
    option java_multiple_files = true;
  14.  
    option java_package = “io.grpc.welife.WshExportTask”;
  15.  
    option java_outer_classname = “WshExportTask”;
  16.  
    // 包名 golang包名,php中namespase,
  17.  
    package exporttask;
  18.  
  19.  
    // 导出任务服务定义
  20.  
    service ExportTask {
  21.  
    // 创建任务模板
  22.  
    rpc CreateTpl(WshExportTaskCreateTplReq) returns (WshExportTaskCreateTplRes) {}
  23.  
    // 查询任务模板
  24.  
    rpc ListTpl(WshExportTaskListTplReq) returns (WshExportTaskListTplRes) {}
  25.  
    }
  26.  
  27.  
    // 枚举类型,必须从0开始,序号可跨越。同一包下不能重名,所以加前缀来区别
  28.  
    enum WshExportTplStatus {
  29.  
    TPL_INITED = 0;
  30.  
    TPL_NORMAL = 1;
  31.  
    TPL_DELETED = 9;
  32.  
    }
  33.  
  34.  
    enum WshExportFormat {
  35.  
    FMT_DEFAULT = 0;
  36.  
    FMT_CSV = 1;
  37.  
    FMT_XLS = 2;
  38.  
    }
  39.  
  40.  
    message WshExportTpl {
  41.  
    string etplName = 1;
  42.  
    string etplTag = 2;
  43.  
    WshExportFormat etplOutputFormat = 3;
  44.  
    string etplOutputColumns = 4;
  45.  
    string etplExpr = 5;
  46.  
    int32 etplId = 6;
  47.  
    int32 etplExecTimes = 7;
  48.  
    int32 etplExecOkTimes = 8;
  49.  
    int32 etplStatus = 9;
  50.  
    string etplCreated = 10;
  51.  
    string etplUpdated = 11;
  52.  
    string etplDeleted = 12;
  53.  
    int32 operatorId = 13;
  54.  
    }
  55.  
  56.  
    message WshExportTaskCreateTplReq {
  57.  
    string etplName = 1;
  58.  
    string etplTag = 2;
  59.  
    string etplExpr = 3;
  60.  
    string etplOutputColumns = 4;
  61.  
    WshExportFormat etplOutputFormat = 5;
  62.  
    int32 operatorId = 6;
  63.  
    }
  64.  
  65.  
    message WshExportTaskCreateTplRes {
  66.  
    string errCode = 1;
  67.  
    string errMsg = 2;
  68.  
    WshExportTpl data = 3;
  69.  
    }
  70.  
  71.  
    message WshExportTaskListTplReq {
  72.  
    int32 etplId = 1;
  73.  
    string etplName = 2;
  74.  
    string etplTag = 3;
  75.  
    }
  76.  
  77.  
    // repeated 表示数组
  78.  
    message WshExportTaskListTplRes {
  79.  
    string errCode = 1;
  80.  
    string errMsg = 2;
  81.  
    repeated WshExportTpl data = 3;
  82.  
    }
  83.  

使用protoc命令生成golang对应的rpc代码:

  1.  
    #格式 protoc –go_out=plugins=grpc:{go代码输出路径} {proto文件}
  2.  
    protoc –go_out=plugins=grpc:./ ./exporttask.proto

生成对应当exporttask.pb.go

  1.  
    // Code generated by protoc-gen-go. DO NOT EDIT.
  2.  
    // source: exporttask.proto
  3.  
  4.  
    /
  5.  
    Package exporttask is a generated protocol buffer package.
  6.  
     
  7.  
    包名 golang包名,php中namespase,
  8.  
     
  9.  
    It is generated from these files:
  10.  
    exporttask.proto
  11.  
     
  12.  
    It has these top-level messages:
  13.  
    WshExportTpl
  14.  
    WshExportTaskCreateTplReq
  15.  
    WshExportTaskCreateTplRes
  16.  
    WshExportTaskListTplReq
  17.  
    WshExportTaskListTplRes
  18.  
    */
  19.  
    package exporttask
  20.  
  21.  
    import proto “github.com/golang/protobuf/proto”
  22.  
    import fmt “fmt”
  23.  
    import math “math”
  24.  
  25.  
    import (
  26.  
    context “golang.org/x/net/context”
  27.  
    grpc “google.golang.org/grpc”
  28.  
    )
  29.  
  30.  
    // Reference imports to suppress errors if they are not otherwise used.
  31.  
    var _ = proto.Marshal
  32.  
    var _ = fmt.Errorf
  33.  
    var _ = math.Inf
  34.  
  35.  
    // This is a compile-time assertion to ensure that this generated file
  36.  
    // is compatible with the proto package it is being compiled against.
  37.  
    // A compilation error at this line likely means your copy of the
  38.  
    // proto package needs to be updated.
  39.  
    const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
  40.  
  41.  
    // 枚举类型,必须从0开始,序号可跨越。同一包下不能重名,所以加前缀来区别
  42.  
    type WshExportTplStatus int32
  43.  
  44.  
    const (
  45.  
    WshExportTplStatus_TPL_INITED WshExportTplStatus = 0
  46.  
    WshExportTplStatus_TPL_NORMAL WshExportTplStatus = 1
  47.  
    WshExportTplStatus_TPL_DELETED WshExportTplStatus = 9
  48.  
    )
  49.  
  50.  
    var WshExportTplStatus_name = map[int32]string{
  51.  
    0: “TPL_INITED”,
  52.  
    1: “TPL_NORMAL”,
  53.  
    9: “TPL_DELETED”,
  54.  
    }
  55.  
    var WshExportTplStatus_value = map[string]int32{
  56.  
    “TPL_INITED”: 0,
  57.  
    “TPL_NORMAL”: 1,
  58.  
    “TPL_DELETED”: 9,
  59.  
    }
  60.  
  61.  
    func (x WshExportTplStatus) String() string {
  62.  
    return proto.EnumName(WshExportTplStatus_name, int32(x))
  63.  
    }
  64.  
    func (WshExportTplStatus) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
  65.  
  66.  
    type WshExportFormat int32
  67.  
  68.  
    const (
  69.  
    WshExportFormat_FMT_DEFAULT WshExportFormat = 0
  70.  
    WshExportFormat_FMT_CSV WshExportFormat = 1
  71.  
    WshExportFormat_FMT_XLS WshExportFormat = 2
  72.  
    )
  73.  
  74.  
    var WshExportFormat_name = map[int32]string{
  75.  
    0: “FMT_DEFAULT”,
  76.  
    1: “FMT_CSV”,
  77.  
    2: “FMT_XLS”,
  78.  
    }
  79.  
    var WshExportFormat_value = map[string]int32{
  80.  
    “FMT_DEFAULT”: 0,
  81.  
    “FMT_CSV”: 1,
  82.  
    “FMT_XLS”: 2,
  83.  
    }
  84.  
  85.  
    func (x WshExportFormat) String() string {
  86.  
    return proto.EnumName(WshExportFormat_name, int32(x))
  87.  
    }
  88.  
    func (WshExportFormat) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
  89.  
  90.  
    type WshExportTpl struct {
  91.  
    EtplName string protobuf:"bytes,1,opt,name=etplName" json:"etplName,omitempty"
  92.  
    EtplTag string protobuf:"bytes,2,opt,name=etplTag" json:"etplTag,omitempty"
  93.  
    EtplOutputFormat WshExportFormat protobuf:"varint,3,opt,name=etplOutputFormat,enum=exporttask.WshExportFormat" json:"etplOutputFormat,omitempty"
  94.  
    EtplOutputColumns string protobuf:"bytes,4,opt,name=etplOutputColumns" json:"etplOutputColumns,omitempty"
  95.  
    EtplExpr string protobuf:"bytes,5,opt,name=etplExpr" json:"etplExpr,omitempty"
  96.  
    EtplId int32 protobuf:"varint,6,opt,name=etplId" json:"etplId,omitempty"
  97.  
    EtplExecTimes int32 protobuf:"varint,7,opt,name=etplExecTimes" json:"etplExecTimes,omitempty"
  98.  
    EtplExecOkTimes int32 protobuf:"varint,8,opt,name=etplExecOkTimes" json:"etplExecOkTimes,omitempty"
  99.  
    EtplStatus int32 protobuf:"varint,9,opt,name=etplStatus" json:"etplStatus,omitempty"
  100.  
    EtplCreated string protobuf:"bytes,10,opt,name=etplCreated" json:"etplCreated,omitempty"
  101.  
    EtplUpdated string protobuf:"bytes,11,opt,name=etplUpdated" json:"etplUpdated,omitempty"
  102.  
    EtplDeleted string protobuf:"bytes,12,opt,name=etplDeleted" json:"etplDeleted,omitempty"
  103.  
    OperatorId int32 protobuf:"varint,13,opt,name=operatorId" json:"operatorId,omitempty"
  104.  
    }
  105.  
  106.  
    func (m *WshExportTpl) Reset() { *m = WshExportTpl{} }
  107.  
    func (m *WshExportTpl) String() string { return proto.CompactTextString(m) }
  108.  
    func (*WshExportTpl) ProtoMessage() {}
  109.  
    func (*WshExportTpl) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
  110.  
  111.  
    func (m *WshExportTpl) GetEtplName() string {
  112.  
    if m != nil {
  113.  
    return m.EtplName
  114.  
    }
  115.  
    return “”
  116.  
    }
  117.  
  118.  
    func (m *WshExportTpl) GetEtplTag() string {
  119.  
    if m != nil {
  120.  
    return m.EtplTag
  121.  
    }
  122.  
    return “”
  123.  
    }
  124.  
  125.  
    func (m *WshExportTpl) GetEtplOutputFormat() WshExportFormat {
  126.  
    if m != nil {
  127.  
    return m.EtplOutputFormat
  128.  
    }
  129.  
    return WshExportFormat_FMT_DEFAULT
  130.  
    }
  131.  
  132.  
    func (m *WshExportTpl) GetEtplOutputColumns() string {
  133.  
    if m != nil {
  134.  
    return m.EtplOutputColumns
  135.  
    }
  136.  
    return “”
  137.  
    }
  138.  
  139.  
    func (m *WshExportTpl) GetEtplExpr() string {
  140.  
    if m != nil {
  141.  
    return m.EtplExpr
  142.  
    }
  143.  
    return “”
  144.  
    }
  145.  
  146.  
    func (m *WshExportTpl) GetEtplId() int32 {
  147.  
    if m != nil {
  148.  
    return m.EtplId
  149.  
    }
  150.  
    return 0
  151.  
    }
  152.  
  153.  
    func (m *WshExportTpl) GetEtplExecTimes() int32 {
  154.  
    if m != nil {
  155.  
    return m.EtplExecTimes
  156.  
    }
  157.  
    return 0
  158.  
    }
  159.  
  160.  
    func (m *WshExportTpl) GetEtplExecOkTimes() int32 {
  161.  
    if m != nil {
  162.  
    return m.EtplExecOkTimes
  163.  
    }
  164.  
    return 0
  165.  
    }
  166.  
  167.  
    func (m *WshExportTpl) GetEtplStatus() int32 {
  168.  
    if m != nil {
  169.  
    return m.EtplStatus
  170.  
    }
  171.  
    return 0
  172.  
    }
  173.  
  174.  
    func (m *WshExportTpl) GetEtplCreated() string {
  175.  
    if m != nil {
  176.  
    return m.EtplCreated
  177.  
    }
  178.  
    return “”
  179.  
    }
  180.  
  181.  
    func (m *WshExportTpl) GetEtplUpdated() string {
  182.  
    if m != nil {
  183.  
    return m.EtplUpdated
  184.  
    }
  185.  
    return “”
  186.  
    }
  187.  
  188.  
    func (m *WshExportTpl) GetEtplDeleted() string {
  189.  
    if m != nil {
  190.  
    return m.EtplDeleted
  191.  
    }
  192.  
    return “”
  193.  
    }
  194.  
  195.  
    func (m *WshExportTpl) GetOperatorId() int32 {
  196.  
    if m != nil {
  197.  
    return m.OperatorId
  198.  
    }
  199.  
    return 0
  200.  
    }
  201.  
  202.  
    type WshExportTaskCreateTplReq struct {
  203.  
    EtplName string protobuf:"bytes,1,opt,name=etplName" json:"etplName,omitempty"
  204.  
    EtplTag string protobuf:"bytes,2,opt,name=etplTag" json:"etplTag,omitempty"
  205.  
    EtplExpr string protobuf:"bytes,3,opt,name=etplExpr" json:"etplExpr,omitempty"
  206.  
    EtplOutputColumns string protobuf:"bytes,4,opt,name=etplOutputColumns" json:"etplOutputColumns,omitempty"
  207.  
    EtplOutputFormat WshExportFormat protobuf:"varint,5,opt,name=etplOutputFormat,enum=exporttask.WshExportFormat" json:"etplOutputFormat,omitempty"
  208.  
    OperatorId int32 protobuf:"varint,6,opt,name=operatorId" json:"operatorId,omitempty"
  209.  
    }
  210.  
  211.  
    func (m *WshExportTaskCreateTplReq) Reset() { *m = WshExportTaskCreateTplReq{} }
  212.  
    func (m *WshExportTaskCreateTplReq) String() string { return proto.CompactTextString(m) }
  213.  
    func (*WshExportTaskCreateTplReq) ProtoMessage() {}
  214.  
    func (*WshExportTaskCreateTplReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
  215.  
  216.  
    func (m *WshExportTaskCreateTplReq) GetEtplName() string {
  217.  
    if m != nil {
  218.  
    return m.EtplName
  219.  
    }
  220.  
    return “”
  221.  
    }
  222.  
  223.  
    func (m *WshExportTaskCreateTplReq) GetEtplTag() string {
  224.  
    if m != nil {
  225.  
    return m.EtplTag
  226.  
    }
  227.  
    return “”
  228.  
    }
  229.  
  230.  
    func (m *WshExportTaskCreateTplReq) GetEtplExpr() string {
  231.  
    if m != nil {
  232.  
    return m.EtplExpr
  233.  
    }
  234.  
    return “”
  235.  
    }
  236.  
  237.  
    func (m *WshExportTaskCreateTplReq) GetEtplOutputColumns() string {
  238.  
    if m != nil {
  239.  
    return m.EtplOutputColumns
  240.  
    }
  241.  
    return “”
  242.  
    }
  243.  
  244.  
    func (m *WshExportTaskCreateTplReq) GetEtplOutputFormat() WshExportFormat {
  245.  
    if m != nil {
  246.  
    return m.EtplOutputFormat
  247.  
    }
  248.  
    return WshExportFormat_FMT_DEFAULT
  249.  
    }
  250.  
  251.  
    func (m *WshExportTaskCreateTplReq) GetOperatorId() int32 {
  252.  
    if m != nil {
  253.  
    return m.OperatorId
  254.  
    }
  255.  
    return 0
  256.  
    }
  257.  
  258.  
    type WshExportTaskCreateTplRes struct {
  259.  
    ErrCode string protobuf:"bytes,1,opt,name=errCode" json:"errCode,omitempty"
  260.  
    ErrMsg string protobuf:"bytes,2,opt,name=errMsg" json:"errMsg,omitempty"
  261.  
    Data *WshExportTpl protobuf:"bytes,3,opt,name=data" json:"data,omitempty"
  262.  
    }
  263.  
  264.  
    func (m *WshExportTaskCreateTplRes) Reset() { *m = WshExportTaskCreateTplRes{} }
  265.  
    func (m *WshExportTaskCreateTplRes) String() string { return proto.CompactTextString(m) }
  266.  
    func (*WshExportTaskCreateTplRes) ProtoMessage() {}
  267.  
    func (*WshExportTaskCreateTplRes) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
  268.  
  269.  
    func (m *WshExportTaskCreateTplRes) GetErrCode() string {
  270.  
    if m != nil {
  271.  
    return m.ErrCode
  272.  
    }
  273.  
    return “”
  274.  
    }
  275.  
  276.  
    func (m *WshExportTaskCreateTplRes) GetErrMsg() string {
  277.  
    if m != nil {
  278.  
    return m.ErrMsg
  279.  
    }
  280.  
    return “”
  281.  
    }
  282.  
  283.  
    func (m *WshExportTaskCreateTplRes) GetData() *WshExportTpl {
  284.  
    if m != nil {
  285.  
    return m.Data
  286.  
    }
  287.  
    return nil
  288.  
    }
  289.  
  290.  
    type WshExportTaskListTplReq struct {
  291.  
    EtplId int32 protobuf:"varint,1,opt,name=etplId" json:"etplId,omitempty"
  292.  
    EtplName string protobuf:"bytes,2,opt,name=etplName" json:"etplName,omitempty"
  293.  
    EtplTag string protobuf:"bytes,3,opt,name=etplTag" json:"etplTag,omitempty"
  294.  
    }
  295.  
  296.  
    func (m *WshExportTaskListTplReq) Reset() { *m = WshExportTaskListTplReq{} }
  297.  
    func (m *WshExportTaskListTplReq) String() string { return proto.CompactTextString(m) }
  298.  
    func (*WshExportTaskListTplReq) ProtoMessage() {}
  299.  
    func (*WshExportTaskListTplReq) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
  300.  
  301.  
    func (m *WshExportTaskListTplReq) GetEtplId() int32 {
  302.  
    if m != nil {
  303.  
    return m.EtplId
  304.  
    }
  305.  
    return 0
  306.  
    }
  307.  
  308.  
    func (m *WshExportTaskListTplReq) GetEtplName() string {
  309.  
    if m != nil {
  310.  
    return m.EtplName
  311.  
    }
  312.  
    return “”
  313.  
    }
  314.  
  315.  
    func (m *WshExportTaskListTplReq) GetEtplTag() string {
  316.  
    if m != nil {
  317.  
    return m.EtplTag
  318.  
    }
  319.  
    return “”
  320.  
    }
  321.  
  322.  
    // repeated 表示数组
  323.  
    type WshExportTaskListTplRes struct {
  324.  
    ErrCode string protobuf:"bytes,1,opt,name=errCode" json:"errCode,omitempty"
  325.  
    ErrMsg string protobuf:"bytes,2,opt,name=errMsg" json:"errMsg,omitempty"
  326.  
    Data []*WshExportTpl protobuf:"bytes,3,rep,name=data" json:"data,omitempty"
  327.  
    }
  328.  
  329.  
    func (m *WshExportTaskListTplRes) Reset() { *m = WshExportTaskListTplRes{} }
  330.  
    func (m *WshExportTaskListTplRes) String() string { return proto.CompactTextString(m) }
  331.  
    func (*WshExportTaskListTplRes) ProtoMessage() {}
  332.  
    func (*WshExportTaskListTplRes) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
  333.  
  334.  
    func (m *WshExportTaskListTplRes) GetErrCode() string {
  335.  
    if m != nil {
  336.  
    return m.ErrCode
  337.  
    }
  338.  
    return “”
  339.  
    }
  340.  
  341.  
    func (m *WshExportTaskListTplRes) GetErrMsg() string {
  342.  
    if m != nil {
  343.  
    return m.ErrMsg
  344.  
    }
  345.  
    return “”
  346.  
    }
  347.  
  348.  
    func (m *WshExportTaskListTplRes) GetData() []*WshExportTpl {
  349.  
    if m != nil {
  350.  
    return m.Data
  351.  
    }
  352.  
    return nil
  353.  
    }
  354.  
  355.  
    func init() {
  356.  
    proto.RegisterType((*WshExportTpl)(nil), “exporttask.WshExportTpl”)
  357.  
    proto.RegisterType((*WshExportTaskCreateTplReq)(nil), “exporttask.WshExportTaskCreateTplReq”)
  358.  
    proto.RegisterType((*WshExportTaskCreateTplRes)(nil), “exporttask.WshExportTaskCreateTplRes”)
  359.  
    proto.RegisterType((*WshExportTaskListTplReq)(nil), “exporttask.WshExportTaskListTplReq”)
  360.  
    proto.RegisterType((*WshExportTaskListTplRes)(nil), “exporttask.WshExportTaskListTplRes”)
  361.  
    proto.RegisterEnum(“exporttask.WshExportTplStatus”, WshExportTplStatus_name, WshExportTplStatus_value)
  362.  
    proto.RegisterEnum(“exporttask.WshExportFormat”, WshExportFormat_name, WshExportFormat_value)
  363.  
    }
  364.  
  365.  
    // Reference imports to suppress errors if they are not otherwise used.
  366.  
    var _ context.Context
  367.  
    var _ grpc.ClientConn
  368.  
  369.  
    // This is a compile-time assertion to ensure that this generated file
  370.  
    // is compatible with the grpc package it is being compiled against.
  371.  
    const _ = grpc.SupportPackageIsVersion4
  372.  
  373.  
    // Client API for ExportTask service
  374.  
  375.  
    type ExportTaskClient interface {
  376.  
    // 创建任务模板
  377.  
    CreateTpl(ctx context.Context, in *WshExportTaskCreateTplReq, opts …grpc.CallOption) (*WshExportTaskCreateTplRes, error)
  378.  
    // 查询任务模板
  379.  
    ListTpl(ctx context.Context, in *WshExportTaskListTplReq, opts …grpc.CallOption) (*WshExportTaskListTplRes, error)
  380.  
    }
  381.  
  382.  
    type exportTaskClient struct {
  383.  
    cc *grpc.ClientConn
  384.  
    }
  385.  
  386.  
    func NewExportTaskClient(cc *grpc.ClientConn) ExportTaskClient {
  387.  
    return &exportTaskClient{cc}
  388.  
    }
  389.  
  390.  
    func (c *exportTaskClient) CreateTpl(ctx context.Context, in *WshExportTaskCreateTplReq, opts …grpc.CallOption) (*WshExportTaskCreateTplRes, error) {
  391.  
    out := new(WshExportTaskCreateTplRes)
  392.  
    err := grpc.Invoke(ctx, “/exporttask.ExportTask/CreateTpl”, in, out, c.cc, opts…)
  393.  
    if err != nil {
  394.  
    return nil, err
  395.  
    }
  396.  
    return out, nil
  397.  
    }
  398.  
  399.  
    func (c *exportTaskClient) ListTpl(ctx context.Context, in *WshExportTaskListTplReq, opts …grpc.CallOption) (*WshExportTaskListTplRes, error) {
  400.  
    out := new(WshExportTaskListTplRes)
  401.  
    err := grpc.Invoke(ctx, “/exporttask.ExportTask/ListTpl”, in, out, c.cc, opts…)
  402.  
    if err != nil {
  403.  
    return nil, err
  404.  
    }
  405.  
    return out, nil
  406.  
    }
  407.  
  408.  
    // Server API for ExportTask service
  409.  
  410.  
    type ExportTaskServer interface {
  411.  
    // 创建任务模板
  412.  
    CreateTpl(context.Context, *WshExportTaskCreateTplReq) (*WshExportTaskCreateTplRes, error)
  413.  
    // 查询任务模板
  414.  
    ListTpl(context.Context, *WshExportTaskListTplReq) (*WshExportTaskListTplRes, error)
  415.  
    }
  416.  
  417.  
    func RegisterExportTaskServer(s *grpc.Server, srv ExportTaskServer) {
  418.  
    s.RegisterService(&_ExportTask_serviceDesc, srv)
  419.  
    }
  420.  
  421.  
    func _ExportTask_CreateTpl_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
  422.  
    in := new(WshExportTaskCreateTplReq)
  423.  
    if err := dec(in); err != nil {
  424.  
    return nil, err
  425.  
    }
  426.  
    if interceptor == nil {
  427.  
    return srv.(ExportTaskServer).CreateTpl(ctx, in)
  428.  
    }
  429.  
    info := &grpc.UnaryServerInfo{
  430.  
    Server: srv,
  431.  
    FullMethod: “/exporttask.ExportTask/CreateTpl”,
  432.  
    }
  433.  
    handler := func(ctx context.Context, req interface{}) (interface{}, error) {
  434.  
    return srv.(ExportTaskServer).CreateTpl(ctx, req.(*WshExportTaskCreateTplReq))
  435.  
    }
  436.  
    return interceptor(ctx, in, info, handler)
  437.  
    }
  438.  
  439.  
    func _ExportTask_ListTpl_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
  440.  
    in := new(WshExportTaskListTplReq)
  441.  
    if err := dec(in); err != nil {
  442.  
    return nil, err
  443.  
    }
  444.  
    if interceptor == nil {
  445.  
    return srv.(ExportTaskServer).ListTpl(ctx, in)
  446.  
    }
  447.  
    info := &grpc.UnaryServerInfo{
  448.  
    Server: srv,
  449.  
    FullMethod: “/exporttask.ExportTask/ListTpl”,
  450.  
    }
  451.  
    handler := func(ctx context.Context, req interface{}) (interface{}, error) {
  452.  
    return srv.(ExportTaskServer).ListTpl(ctx, req.(*WshExportTaskListTplReq))
  453.  
    }
  454.  
    return interceptor(ctx, in, info, handler)
  455.  
    }
  456.  
  457.  
    var _ExportTask_serviceDesc = grpc.ServiceDesc{
  458.  
    ServiceName: “exporttask.ExportTask”,
  459.  
    HandlerType: (*ExportTaskServer)(nil),
  460.  
    Methods: []grpc.MethodDesc{
  461.  
    {
  462.  
    MethodName: “CreateTpl”,
  463.  
    Handler: _ExportTask_CreateTpl_Handler,
  464.  
    },
  465.  
    {
  466.  
    MethodName: “ListTpl”,
  467.  
    Handler: _ExportTask_ListTpl_Handler,
  468.  
    },
  469.  
    },
  470.  
    Streams: []grpc.StreamDesc{},
  471.  
    Metadata: “exporttask.proto”,
  472.  
    }
  473.  
  474.  
    func init() { proto.RegisterFile(“exporttask.proto”, fileDescriptor0) }
  475.  
  476.  
    var fileDescriptor0 = []byte{
  477.  
    // 550 bytes of a gzipped FileDescriptorProto
  478.  
    0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xa4, 0x54, 0x5f, 0x8f, 0xd2, 0x4e,
  479.  
    0x14, 0xa5, 0xb0, 0xc0, 0x72, 0x59, 0x96, 0xfe, 0xe6, 0xe1, 0xe7, 0x88, 0xc6, 0x90, 0xaa, 0x09,
  480.  
    0xd9, 0x6c, 0x30, 0xc1, 0x57, 0x5f, 0x76, 0xa1, 0x18, 0x92, 0x02, 0x1b, 0x28, 0x6a, 0xe2, 0xc3,
  481.  
    0xa6, 0x6e, 0x47, 0x24, 0x14, 0x5b, 0x67, 0x86, 0xb8, 0xc6, 0x57, 0x3f, 0x98, 0x5f, 0xc6, 0xef,
  482.  
    0x61, 0x66, 0xda, 0x61, 0x5a, 0xfe, 0xc4, 0x75, 0x7d, 0x9b, 0x73, 0xe6, 0x94, 0x7b, 0xef, 0x39,
  483.  
    0x77, 0x00, 0x93, 0xdc, 0x46, 0x21, 0xe5, 0xdc, 0x63, 0xcb, 0x76, 0x44, 0x43, 0x1e, 0x22, 0xd0,
  484.  
    0x8c, 0xf5, 0xab, 0x00, 0x27, 0x6f, 0xd9, 0x27, 0x5b, 0x32, 0x6e, 0x14, 0xa0, 0x06, 0x1c, 0x13,
  485.  
    0x1e, 0x05, 0x23, 0x6f, 0x45, 0xb0, 0xd1, 0x34, 0x5a, 0x95, 0xc9, 0x06, 0x23, 0x0c, 0x65, 0x71,
  486.  
    0x76, 0xbd, 0x39, 0xce, 0xcb, 0x2b, 0x05, 0xd1, 0x6b, 0x30, 0xc5, 0x71, 0xbc, 0xe6, 0xd1, 0x9a,
  487.  
    0xf7, 0x43, 0xba, 0xf2, 0x38, 0x2e, 0x34, 0x8d, 0xd6, 0x69, 0xe7, 0x51, 0x3b, 0x55, 0x7f, 0x53,
  488.  
    0x29, 0x96, 0x4c, 0x76, 0x3e, 0x42, 0xe7, 0xf0, 0x9f, 0xe6, 0xba, 0x61, 0xb0, 0x5e, 0x7d, 0x66,
  489.  
    0xf8, 0x48, 0x16, 0xdb, 0xbd, 0x50, 0xcd, 0xda, 0xb7, 0x11, 0xc5, 0x45, 0xdd, 0xac, 0xc0, 0xe8,
  490.  
    0x7f, 0x28, 0x89, 0xf3, 0xc0, 0xc7, 0xa5, 0xa6, 0xd1, 0x2a, 0x4e, 0x12, 0x84, 0x9e, 0x41, 0x2d,
  491.  
    0xd6, 0x90, 0x1b, 0x77, 0xb1, 0x22, 0x0c, 0x97, 0xe5, 0x75, 0x96, 0x44, 0x2d, 0xa8, 0x2b, 0x62,
  492.  
    0xbc, 0x8c, 0x75, 0xc7, 0x52, 0xb7, 0x4d, 0xa3, 0x27, 0x00, 0x82, 0x9a, 0x72, 0x8f, 0xaf, 0x19,
  493.  
    0xae, 0x48, 0x51, 0x8a, 0x41, 0x4d, 0xa8, 0x0a, 0xd4, 0xa5, 0xc4, 0xe3, 0xc4, 0xc7, 0x20, 0xdb,
  494.  
    0x4c, 0x53, 0x4a, 0x31, 0x8b, 0x7c, 0xa9, 0xa8, 0x6a, 0x45, 0x42, 0x29, 0x45, 0x8f, 0x04, 0x44,
  495.  
    0x28, 0x4e, 0xb4, 0x22, 0xa1, 0x44, 0x17, 0x61, 0x44, 0xa8, 0xc7, 0x43, 0x3a, 0xf0, 0x71, 0x2d,
  496.  
    0xee, 0x42, 0x33, 0xd6, 0x8f, 0x3c, 0x3c, 0xd4, 0x39, 0x7b, 0x6c, 0x19, 0x17, 0x77, 0xa3, 0x60,
  497.  
    0x42, 0xbe, 0xdc, 0x33, 0xf4, 0xb4, 0xfb, 0x85, 0x2d, 0xf7, 0xff, 0x2e, 0xc7, 0x7d, 0xeb, 0x53,
  498.  
    0xbc, 0xcf, 0xfa, 0x64, 0x6d, 0x28, 0xed, 0xd8, 0xf0, 0xfd, 0xb0, 0x0b, 0x4c, 0x4e, 0x4a, 0x69,
  499.  
    0x37, 0xf4, 0x95, 0x09, 0x0a, 0xca, 0x5d, 0xa2, 0x74, 0xc8, 0x94, 0x05, 0x09, 0x42, 0xe7, 0x70,
  500.  
    0xe4, 0x7b, 0xdc, 0x93, 0xd3, 0x57, 0x3b, 0x78, 0x6f, 0xaf, 0xe2, 0xc7, 0xa5, 0xca, 0x9a, 0xc3,
  501.  
    0x83, 0x4c, 0x71, 0x67, 0xc1, 0x78, 0x12, 0x80, 0x5e, 0x56, 0x23, 0xb3, 0xac, 0xe9, 0x60, 0xf2,
  502.  
    0x87, 0x83, 0x29, 0x64, 0x82, 0xb1, 0xbe, 0x1d, 0x2a, 0xf4, 0x6f, 0x33, 0x16, 0xfe, 0x3c, 0xe3,
  503.  
    0x99, 0x0d, 0x28, 0xcd, 0x26, 0x6f, 0xe0, 0x14, 0xc0, 0xbd, 0x72, 0xae, 0x07, 0xa3, 0x81, 0x6b,
  504.  
    0xf7, 0xcc, 0x9c, 0xc2, 0xa3, 0xf1, 0x64, 0x78, 0xe1, 0x98, 0x06, 0xaa, 0x43, 0x55, 0xe0, 0x9e,
  505.  
    0xed, 0xd8, 0x42, 0x50, 0x39, 0x7b, 0x05, 0xf5, 0xad, 0xb0, 0x85, 0xa6, 0x3f, 0x74, 0xaf, 0x7b,
  506.  
    0x76, 0xff, 0x62, 0xe6, 0xb8, 0x66, 0x0e, 0x55, 0xa1, 0x2c, 0x88, 0xee, 0xf4, 0x8d, 0x69, 0x28,
  507.  
    0xf0, 0xce, 0x99, 0x9a, 0xf9, 0xce, 0x4f, 0x03, 0x40, 0x4f, 0x8f, 0xde, 0x43, 0x65, 0x93, 0x33,
  508.  
    0x7a, 0xbe, 0x7f, 0x80, 0xad, 0x17, 0xd1, 0xb8, 0x93, 0x8c, 0x59, 0x39, 0x34, 0x83, 0x72, 0x62,
  509.  
    0x2f, 0x7a, 0x7a, 0xf0, 0x1b, 0x9d, 0x74, 0xe3, 0x0e, 0x22, 0x66, 0xe5, 0x2e, 0x5f, 0xc0, 0xe3,
  510.  
    0x45, 0xd8, 0x9e, 0xd3, 0xe8, 0xa6, 0xfd, 0x95, 0x04, 0x8b, 0x8f, 0x24, 0xab, 0xbd, 0xac, 0x65,
  511.  
    0xe0, 0x95, 0xf1, 0xa1, 0x24, 0xff, 0xdb, 0x5f, 0xfe, 0x0e, 0x00, 0x00, 0xff, 0xff, 0x60, 0x9b,
  512.  
    0xec, 0x89, 0xef, 0x05, 0x00, 0x00,
  513.  
    }

服务端实现proto中的接口:

  1.  
    package main
  2.  
  3.  
    import (
  4.  
    “log”
  5.  
    //“net”
  6.  
  7.  
    svcExport “../../common/exporttask” // 包含上面的pb生成的go包
  8.  
    “./model”
  9.  
    _ “github.com/go-sql-driver/mysql”
  10.  
    “golang.org/x/net/context”
  11.  
    //“google.golang.org/grpc”
  12.  
    //“google.golang.org/grpc/reflection”
  13.  
    )
  14.  
  15.  
    // server 这个对象来实现 exporttask 包中的pb定义的rpc服务
  16.  
    // 实现的方式是将服务转化成本地的数据库操作
  17.  
    type server struct{}
  18.  
  19.  
    func (s *server) CreateTpl(ctx context.Context, in *svcExport.WshExportTaskCreateTplReq) (res *svcExport.WshExportTaskCreateTplRes, err error) {
  20.  
    res = new(svcExport.WshExportTaskCreateTplRes)
  21.  
    res.Data = new(svcExport.WshExportTpl)
  22.  
  23.  
    var etplId int32 = 0
  24.  
  25.  
    etplId, err = model.CreateTpl(in.EtplName, in.EtplTag, in.EtplExpr, in.EtplOutputColumns, int32(in.EtplOutputFormat), in.OperatorId)
  26.  
    //res.Data, err = model.GetTpl(etplId)
  27.  
    res.Data.EtplId = etplId
  28.  
    return res, err
  29.  
    }
  30.  
  31.  
    func (s *server) ListTpl(ctx context.Context, in *svcExport.WshExportTaskListTplReq) (*svcExport.WshExportTaskListTplRes, error) {
  32.  
    res := new(svcExport.WshExportTaskListTplRes)
  33.  
    entList, err := model.ListTpl(in.EtplId, in.EtplName, in.EtplTag)
  34.  
  35.  
    if err != nil {
  36.  
    res.ErrMsg = err.Error()
  37.  
    res.ErrCode = “2”
  38.  
    }
  39.  
  40.  
    for _, ent := range entList {
  41.  
    t := new(svcExport.WshExportTpl)
  42.  
    ent.CopyToPb(t)
  43.  
    res.Data = append(res.Data, t)
  44.  
    }
  45.  
  46.  
    return res, err
  47.  
    }
  48.  
  49.  

服务端main启动服务main.go

  1.  
    /
  2.  
    * exporttask server main
  3.  
    * $ go build exporttask.go
  4.  
    */
  5.  
    package main
  6.  
  7.  
    import (
  8.  
    “log”
  9.  
    “net”
  10.  
  11.  
    svcExport “../../common/exporttask”
  12.  
    //“./model”
  13.  
    _ “github.com/go-sql-driver/mysql”
  14.  
    //“golang.org/x/net/context”
  15.  
    “google.golang.org/grpc”
  16.  
    “google.golang.org/grpc/reflection”
  17.  
    )
  18.  
  19.  
    const (
  20.  
    port = “:50051”
  21.  
    )
  22.  
  23.  
    func main() {
  24.  
    lis, err := net.Listen(“tcp”, port)
  25.  
    if err != nil {
  26.  
    log.Fatalf(“failed to listen: %v”, err)
  27.  
    }
  28.  
    // 生成一个rpc服务器
  29.  
    s := grpc.NewServer()
  30.  
    // 使用pb包调用注册已实现的rpc接口类server
  31.  
    svcExport.RegisterExportTaskServer(s, &server{})
  32.  
    // Register reflection service on gRPC server.
  33.  
    reflection.Register(s)
  34.  
    if err := s.Serve(lis); err != nil {
  35.  
    log.Fatalf(“failed to serve: %v”, err)
  36.  
    }
  37.  
    }

  Golang gRPC客户端

客户端的代码相对比较简单

  1.  
    package main
  2.  
  3.  
    import (
  4.  
    “flag”
  5.  
    “log”
  6.  
    “os”
  7.  
  8.  
    svcExport “../../common/exporttask”
  9.  
    “golang.org/x/net/context”
  10.  
    “google.golang.org/grpc”
  11.  
    )
  12.  
  13.  
    const (
  14.  
    address = “127.0.0.1:50052”
  15.  
    defaultName = “world”
  16.  
    )
  17.  
  18.  
    func main() {
  19.  
  20.  
    // 发起链接
  21.  
    conn, err := grpc.Dial(address, grpc.WithInsecure())
  22.  
    if err != nil {
  23.  
    log.Fatalf(“did not connect: %v”, err)
  24.  
    }
  25.  
    defer conn.Close()
  26.  
  27.  
    // 创建pb包的客户端
  28.  
    c := svcExport.NewExportTaskClient(conn)
  29.  
  30.  
    name := defaultName
  31.  
    if len(os.Args) > 1 {
  32.  
    name = os.Args[1]
  33.  
    }
  34.  
  35.  
    // 发起请求
  36.  
    var r2 *svcExport.WshExportTaskCreateTplRes
  37.  
    req := svcExport.WshExportTaskCreateTplReq{EtplName: name, EtplTag: “mall”, EtplExpr: “select EtplName from welife_export_tpl”, EtplOutputFormat: svcExport.WshExportFormat_FMT_CSV, EtplOutputColumns: “”}
  38.  
    r2, err = c.CreateTpl(context.Background(), &req)
  39.  
    // 打印结果
  40.  
    log.Println(“create tpl: r=”, r2, err)
  41.  
    }

  php中使用gRPC

php需要安装grpc扩展。
使用protoc命令生成对应的php代码:

protoc –php_out=plugins=grpc:./ exporttask.proto
  • 1
  • 2

生成代码包括:

  1.  
    Exporttask/
  2.  
    |-WshExportFormat.php
  3.  
    |-WshExportTaskCreateTplReq.php
  4.  
    |-WshExportTaskCreateTplRes.php
  5.  
    |-WshExportTaskListTplReq.php
  6.  
    |-WshExportTaskListTplRes.php
  7.  
    |-WshExportTpl.php
  8.  
    -WshExportTplStatus.php
  9.  
    GPBMetadata/
  10.  
    -Exporttask.php

每一个message对应生成一个类,在Exporttask命名空间下。
这里就不都贴出来了,只贴一个WshExportTpl.php:

  1.  
    <?php
  2.  
    # Generated by the protocol buffer compiler. DO NOT EDIT!
  3.  
    # source: exporttask.proto
  4.  
  5.  
    namespace Exporttask;
  6.  
  7.  
    use Google\Protobuf\Internal\GPBType;
  8.  
    use Google\Protobuf\Internal\RepeatedField;
  9.  
    use Google\Protobuf\Internal\GPBUtil;
  10.  
  11.  
    /
  12.  
    * Protobuf type <code>exporttask.WshExportTpl</code>
  13.  
    */
  14.  
    class WshExportTpl extends \Google\Protobuf\Internal\Message
  15.  
    {
  16.  
    /
  17.  
    * <code>string etplName = 1;</code>
  18.  
    */
  19.  
    private $etplName = “;
  20.  
    /
  21.  
    * <code>string etplTag = 2;</code>
  22.  
    */
  23.  
    private $etplTag = “;
  24.  
    /
  25.  
    * <code>.exporttask.WshExportFormat etplOutputFormat = 3;</code>
  26.  
    */
  27.  
    private $etplOutputFormat = 0;
  28.  
    /
  29.  
    * <code>string etplOutputColumns = 4;</code>
  30.  
    */
  31.  
    private $etplOutputColumns = “;
  32.  
    /
  33.  
    * <code>string etplExpr = 5;</code>
  34.  
    */
  35.  
    private $etplExpr = “;
  36.  
    /
  37.  
    * <code>int32 etplId = 6;</code>
  38.  
    */
  39.  
    private $etplId = 0;
  40.  
    /
  41.  
    * <code>int32 etplExecTimes = 7;</code>
  42.  
    */
  43.  
    private $etplExecTimes = 0;
  44.  
    /
  45.  
    * <code>int32 etplExecOkTimes = 8;</code>
  46.  
    */
  47.  
    private $etplExecOkTimes = 0;
  48.  
    /
  49.  
    * <code>int32 etplStatus = 9;</code>
  50.  
    */
  51.  
    private $etplStatus = 0;
  52.  
    /
  53.  
    * <code>string etplCreated = 10;</code>
  54.  
    */
  55.  
    private $etplCreated = “;
  56.  
    /
  57.  
    * <code>string etplUpdated = 11;</code>
  58.  
    */
  59.  
    private $etplUpdated = “;
  60.  
    /
  61.  
    * <code>string etplDeleted = 12;</code>
  62.  
    */
  63.  
    private $etplDeleted = “;
  64.  
    /
  65.  
    * <code>int32 operatorId = 13;</code>
  66.  
    */
  67.  
    private $operatorId = 0;
  68.  
  69.  
    public function construct() {
  70.  
    \GPBMetadata\Exporttask::initOnce();
  71.  
    parent::construct();
  72.  
    }
  73.  
  74.  
    /
  75.  
    * <code>string etplName = 1;</code>
  76.  
    */
  77.  
    public function getEtplName()
  78.  
    {
  79.  
    return $this->etplName;
  80.  
    }
  81.  
  82.  
    /**
  83.  
    * <code>string etplName = 1;</code>
  84.  
    */
  85.  
    public function setEtplName($var)
  86.  
    {
  87.  
    GPBUtil::checkString($var, True);
  88.  
    $this->etplName = $var;
  89.  
    }
  90.  
    // … 其他省略
  1.  
    <?php
  2.  
    $client = new \Exporttask\GreeterClient(‘127.0.0.1:50051’, [
  3.  
    ‘credentials’ => \Grpc\ChannelCredentials::createInsecure(),
  4.  
    ]);
  5.  
    $request = new Exporttask\WshExportTaskCreateTplReq();
  6.  
    $request->setEtplName($name);
  7.  
    list($reply, $status) = $client->createTpl($request)->wait();
  8.  
    $message = $reply->getMessage();
  9.  
    var_dump($message);

  gRPC服务发现与服务治理的方案

目前gRPC主流分布式方案有这么几种: etcd, zookeeper, consul.

  1、集中式LB(Proxy Model)

LB 
在服务消费者和服务提供者之间有一个独立的LB,通常是专门的硬件设备如 F5,或者基于软件如 LVS,HAproxy等实现。LB上有所有服务的地址映射表,通常由运维配置注册,当服务消费方调用某个目标服务时,它向LB发起请求,由LB以某种策略,比如轮询(Round-Robin)做负载均衡后将请求转发到目标服务。LB一般具备健康检查能力,能自动摘除不健康的服务实例。 该方案主要问题:

  • 1、 单点问题,所有服务调用流量都经过LB,当服务数量和调用量大的时候,LB容易成为瓶颈,且一旦LB发生故障影响整个系统;
  • 2、服务消费方、提供方之间增加了一级,有一定性能开销。

  2、进程内LB(Balancing-aware Client)

 
针对第一个方案的不足,此方案将LB的功能集成到服务消费方进程里,也被称为软负载或者客户端负载方案。服务提供方启动时,首先将服务地址注册到服务注册表,同时定期报心跳到服务注册表以表明服务的存活状态,相当于健康检查,服务消费方要访问某个服务时,它通过内置的LB组件向服务注册表查询,同时缓存并定期刷新目标服务地址列表,然后以某种负载均衡策略选择一个目标服务地址,最后向目标服务发起请求。LB和服务发现能力被分散到每一个服务消费者的进程内部,同时服务消费方和服务提供方之间是直接调用,没有额外开销,性能比较好。该方案主要问题:

  • 1、开发成本,该方案将服务调用方集成到客户端的进程里头,如果有多种不同的语言栈,就要配合开发多种不同的客户端,有一定的研发和维护成本;
  • 2、另外生产环境中,后续如果要对客户库进行升级,势必要求服务调用方修改代码并重新发布,升级较复杂。

  3、独立 LB 进程(External Load Balancing Service)

 
该方案是针对第二种方案的不足而提出的一种折中方案,原理和第二种方案基本类似。
不同之处是将LB和服务发现功能从进程内移出来,变成主机上的一个独立进程。主机上的一个或者多个服务要访问目标服务时,他们都通过同一主机上的独立LB进程做服务发现和负载均衡。该方案也是一种分布式方案没有单点问题,一个LB进程挂了只影响该主机上的服务调用方,服务调用方和LB之间是进程内调用性能好,同时该方案还简化了服务调用方,不需要为不同语言开发客户库,LB的升级不需要服务调用方改代码。
该方案主要问题:部署较复杂,环节多,出错调试排查问题不方便。

  服务发现负载均衡实现

gRPC开源组件官方并未直接提供服务注册与发现的功能实现,但其设计文档已提供实现的思路,并在不同语言的gRPC代码API中已提供了命名解析和负载均衡接口供扩展。

其基本实现原理:

  • 1、服务启动后gRPC客户端向命名服务器发出名称解析请求,名称将解析为一个或多个IP地址,每个IP地址标示它是服务器地址还是负载均衡器地址,以及标示要使用那个客户端负载均衡策略或服务配置。
  • 2、客户端实例化负载均衡策略,如果解析返回的地址是负载均衡器地址,则客户端将使用grpclb策略,否则客户端使用服务配置请求的负载均衡策略。
  • 3、负载均衡策略为每个服务器地址创建一个子通道(channel)。
  • 4、当有rpc请求时,负载均衡策略决定那个子通道即grpc服务器将接收请求,当可用服务器为空时客户端的请求将被阻塞。

根据gRPC官方提供的设计思路,基于进程内LB方案(即第2个案,阿里开源的服务框架 Dubbo 也是采用类似机制),结合分布式一致的组件(如Zookeeper、Consul、Etcd),可找到gRPC服务发现和负载均衡的可行解决方案。接下来以GO语言为例,简单介绍下基于Etcd3的关键代码实现:

1)命名解析实现:resolver.go

  1.  
    package etcdv3
  2.  
  3.  
    import (
  4.  
    “errors”
  5.  
    “fmt”
  6.  
    “strings”
  7.  
  8.  
    etcd3 “github.com/coreos/etcd/clientv3”
  9.  
    “google.golang.org/grpc/naming”
  10.  
    )
  11.  
  12.  
    // resolver is the implementaion of grpc.naming.Resolver
  13.  
    type resolver struct {
  14.  
    serviceName string // service name to resolve
  15.  
    }
  16.  
  17.  
    // NewResolver return resolver with service name
  18.  
    func NewResolver(serviceName string) *resolver {
  19.  
    return &resolver{serviceName: serviceName}
  20.  
    }
  21.  
  22.  
    // Resolve to resolve the service from etcd, target is the dial address of etcd
  23.  
  24.  
    func (re *resolver) Resolve(target string) (naming.Watcher, error) {
  25.  
    if re.serviceName == “” {
  26.  
    return nil, errors.New(“grpclb: no service name provided”)
  27.  
    }
  28.  
  29.  
    // generate etcd client
  30.  
    client, err := etcd3.New(etcd3.Config{
  31.  
    Endpoints: strings.Split(target, “,”),
  32.  
    })
  33.  
    if err != nil {
  34.  
    return nil, fmt.Errorf(“grpclb: creat etcd3 client failed: %s”, err.Error())
  35.  
    }
  36.  
  37.  
    // Return watcher
  38.  
    return &watcher{re: re, client: *client}, nil
  39.  
    }

2)服务发现实现:watcher.go

  1.  
    package etcdv3
  2.  
  3.  
    import (
  4.  
    “fmt”
  5.  
    etcd3 “github.com/coreos/etcd/clientv3”
  6.  
    “golang.org/x/net/context”
  7.  
    “google.golang.org/grpc/naming”
  8.  
    “github.com/coreos/etcd/mvcc/mvccpb”
  9.  
    )
  10.  
  11.  
    // watcher is the implementaion of grpc.naming.Watcher
  12.  
    type watcher struct {
  13.  
    re *resolver // re: Etcd Resolver
  14.  
    client etcd3.Client
  15.  
    isInitialized bool
  16.  
    }
  17.  
  18.  
    // Close do nothing
  19.  
    func (w *watcher) Close() {
  20.  
    }
  21.  
  22.  
    // Next to return the updates
  23.  
    func (w *watcher) Next() ([]*naming.Update, error) {
  24.  
    // prefix is the etcd prefix/value to watch
  25.  
    prefix := fmt.Sprintf(“/%s/%s/”, Prefix, w.re.serviceName)
  26.  
  27.  
    // check if is initialized
  28.  
    if !w.isInitialized {
  29.  
    // query addresses from etcd
  30.  
    resp, err := w.client.Get(context.Background(), prefix, etcd3.WithPrefix())
  31.  
    w.isInitialized = true
  32.  
    if err == nil {
  33.  
    addrs := extractAddrs(resp)
  34.  
    //if not empty, return the updates or watcher new dir
  35.  
    if l := len(addrs); l != 0 {
  36.  
    updates := make([]*naming.Update, l)
  37.  
    for i := range addrs {
  38.  
    updates[i] = &naming.Update{Op: naming.Add, Addr: addrs[i]}
  39.  
    }
  40.  
    return updates, nil
  41.  
    }
  42.  
    }
  43.  
    }
  44.  
  45.  
    // generate etcd Watcher
  46.  
    rch := w.client.Watch(context.Background(), prefix, etcd3.WithPrefix())
  47.  
    for wresp := range rch {
  48.  
    for _, ev := range wresp.Events {
  49.  
    switch ev.Type {
  50.  
    case mvccpb.PUT:
  51.  
    return []*naming.Update{{Op: naming.Add, Addr: string(ev.Kv.Value)}}, nil
  52.  
    case mvccpb.DELETE:
  53.  
    return []*naming.Update{{Op: naming.Delete, Addr: string(ev.Kv.Value)}}, nil
  54.  
    }
  55.  
    }
  56.  
    }
  57.  
    return nil, nil
  58.  
    }
  59.  
  60.  
    func extractAddrs(resp *etcd3.GetResponse) []string {
  61.  
    addrs := []string{}
  62.  
  63.  
    if resp == nil || resp.Kvs == nil {
  64.  
    return addrs
  65.  
    }
  66.  
  67.  
    for i := range resp.Kvs {
  68.  
    if v := resp.Kvs[i].Value; v != nil {
  69.  
    addrs = append(addrs, string(v))
  70.  
    }
  71.  
    }
  72.  
  73.  
    return addrs
  74.  
    }

3)服务注册实现:register.go

  1.  
    package etcdv3
  2.  
  3.  
    import (
  4.  
    “fmt”
  5.  
    “log”
  6.  
    “strings”
  7.  
    “time”
  8.  
  9.  
    etcd3 “github.com/coreos/etcd/clientv3”
  10.  
    “golang.org/x/net/context”
  11.  
    “github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes”
  12.  
    )
  13.  
  14.  
    // Prefix should start and end with no slash
  15.  
    var Prefix = “etcd3_naming”
  16.  
    var client etcd3.Client
  17.  
    var serviceKey string
  18.  
  19.  
    var stopSignal = make(chan bool, 1)
  20.  
  21.  
    // Register
  22.  
    func Register(name string, host string, port int, target string, interval time.Duration, ttl int) error {
  23.  
    serviceValue := fmt.Sprintf(“%s:%d”, host, port)
  24.  
    serviceKey = fmt.Sprintf(“/%s/%s/%s”, Prefix, name, serviceValue)
  25.  
  26.  
    // get endpoints for register dial address
  27.  
    var err error
  28.  
    client, err := etcd3.New(etcd3.Config{
  29.  
    Endpoints: strings.Split(target, “,”),
  30.  
    })
  31.  
    if err != nil {
  32.  
    return fmt.Errorf(“grpclb: create etcd3 client failed: %v”, err)
  33.  
    }
  34.  
  35.  
    go func() {
  36.  
    // invoke self-register with ticker
  37.  
    ticker := time.NewTicker(interval)
  38.  
    for {
  39.  
    // minimum lease TTL is ttl-second
  40.  
    resp, _ := client.Grant(context.TODO(), int64(ttl))
  41.  
    // should get first, if not exist, set it
  42.  
    _, err := client.Get(context.Background(), serviceKey)
  43.  
    if err != nil {
  44.  
    if err == rpctypes.ErrKeyNotFound {
  45.  
    if _, err := client.Put(context.TODO(), serviceKey, serviceValue, etcd3.WithLease(resp.ID)); err != nil {
  46.  
    log.Printf(“grpclb: set service ‘%s’ with ttl to etcd3 failed: %s”, name, err.Error())
  47.  
    }
  48.  
    } else {
  49.  
    log.Printf(“grpclb: service ‘%s’ connect to etcd3 failed: %s”, name, err.Error())
  50.  
    }
  51.  
    } else {
  52.  
    // refresh set to true for not notifying the watcher
  53.  
    if _, err := client.Put(context.Background(), serviceKey, serviceValue, etcd3.WithLease(resp.ID)); err != nil {
  54.  
    log.Printf(“grpclb: refresh service ‘%s’ with ttl to etcd3 failed: %s”, name, err.Error())
  55.  
    }
  56.  
    }
  57.  
    select {
  58.  
    case <-stopSignal:
  59.  
    return
  60.  
    case <-ticker.C:
  61.  
    }
  62.  
    }
  63.  
    }()
  64.  
  65.  
    return nil
  66.  
    }
  67.  
  68.  
    // UnRegister delete registered service from etcd
  69.  
    func UnRegister() error {
  70.  
    stopSignal <- true
  71.  
    stopSignal = make(chan bool, 1) // just a hack to avoid multi UnRegister deadlock
  72.  
    var err error;
  73.  
    if _, err := client.Delete(context.Background(), serviceKey); err != nil {
  74.  
    log.Printf(“grpclb: deregister ‘%s’ failed: %s”, serviceKey, err.Error())
  75.  
    } else {
  76.  
    log.Printf(“grpclb: deregister ‘%s’ ok.”, serviceKey)
  77.  
    }
  78.  
    return err
  79.  
    }

4)接口描述文件:helloworld.proto

  1.  
    syntax = “proto3”;
  2.  
  3.  
    option java_multiple_files = true;
  4.  
    option java_package = “com.midea.jr.test.grpc”;
  5.  
    option java_outer_classname = “HelloWorldProto”;
  6.  
    option objc_class_prefix = “HLW”;
  7.  
  8.  
    package helloworld;
  9.  
  10.  
    // The greeting service definition.
  11.  
    service Greeter {
  12.  
    // Sends a greeting
  13.  
    rpc SayHello (HelloRequest) returns (HelloReply) {
  14.  
    }
  15.  
    }
  16.  
  17.  
    // The request message containing the user’s name.
  18.  
    message HelloRequest {
  19.  
    string name = 1;
  20.  
    }
  21.  
  22.  
    // The response message containing the greetings
  23.  
    message HelloReply {
  24.  
    string message = 1;
  25.  
    }

5)实现服务端接口:helloworldserver.go

  1.  
    package main
  2.  
  3.  
    import (
  4.  
    “flag”
  5.  
    “fmt”
  6.  
    “log”
  7.  
    “net”
  8.  
    “os”
  9.  
    “os/signal”
  10.  
    “syscall”
  11.  
    “time”
  12.  
  13.  
    “golang.org/x/net/context”
  14.  
    “google.golang.org/grpc”
  15.  
  16.  
    grpclb “com.midea/jr/grpclb/naming/etcd/v3”
  17.  
    “com.midea/jr/grpclb/example/pb”
  18.  
    )
  19.  
  20.  
    var (
  21.  
    serv = flag.String(“service”, “hello_service”, “service name”)
  22.  
    port = flag.Int(“port”, 50001, “listening port”)
  23.  
    reg = flag.String(“reg”, “http://127.0.0.1:2379”, “register etcd address”)
  24.  
    )
  25.  
  26.  
    func main() {
  27.  
    flag.Parse()
  28.  
  29.  
    lis, err := net.Listen(“tcp”, fmt.Sprintf(“0.0.0.0:%d”, *port))
  30.  
    if err != nil {
  31.  
    panic(err)
  32.  
    }
  33.  
  34.  
    err = grpclb.Register(*serv, “127.0.0.1”, *port, *reg, time.Second*10, 15)
  35.  
    if err != nil {
  36.  
    panic(err)
  37.  
    }
  38.  
  39.  
    ch := make(chan os.Signal, 1)
  40.  
    signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL, syscall.SIGHUP, syscall.SIGQUIT)
  41.  
    go func() {
  42.  
    s := <-ch
  43.  
    log.Printf(“receive signal ‘%v’”, s)
  44.  
    grpclb.UnRegister()
  45.  
    os.Exit(1)
  46.  
    }()
  47.  
  48.  
    log.Printf(“starting hello service at %d”, *port)
  49.  
    s := grpc.NewServer()
  50.  
    pb.RegisterGreeterServer(s, &server{})
  51.  
    s.Serve(lis)
  52.  
    }
  53.  
  54.  
    // server is used to implement helloworld.GreeterServer.
  55.  
    type server struct{}
  56.  
  57.  
    // SayHello implements helloworld.GreeterServer
  58.  
    func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
  59.  
    fmt.Printf(“%v: Receive is %s\n”, time.Now(), in.Name)
  60.  
    return &pb.HelloReply{Message: “Hello ” + in.Name}, nil
  61.  
    }

6)实现客户端接口:helloworldclient.go

  1.  
    package main
  2.  
  3.  
    import (
  4.  
    “flag”
  5.  
    “fmt”
  6.  
    “time”
  7.  
  8.  
    grpclb “com.midea/jr/grpclb/naming/etcd/v3”
  9.  
    “com.midea/jr/grpclb/example/pb”
  10.  
    “golang.org/x/net/context”
  11.  
    “google.golang.org/grpc”
  12.  
    “strconv”
  13.  
    )
  14.  
  15.  
    var (
  16.  
    serv = flag.String(“service”, “hello_service”, “service name”)
  17.  
    reg = flag.String(“reg”, “http://127.0.0.1:2379”, “register etcd address”)
  18.  
    )
  19.  
  20.  
    func main() {
  21.  
    flag.Parse()
  22.  
    r := grpclb.NewResolver(*serv)
  23.  
    b := grpc.RoundRobin®
  24.  
  25.  
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
  26.  
    conn, err := grpc.DialContext(ctx, *reg, grpc.WithInsecure(), grpc.WithBalancer(b))
  27.  
    if err != nil {
  28.  
    panic(err)
  29.  
    }
  30.  
  31.  
    ticker := time.NewTicker(1 * time.Second)
  32.  
    for t := range ticker.C {
  33.  
    client := pb.NewGreeterClient(conn)
  34.  
    resp, err := client.SayHello(context.Background(), &pb.HelloRequest{Name: “world ” + strconv.Itoa(t.Second())})
  35.  
    if err == nil {
  36.  
    fmt.Printf(“%v: Reply is %s\n”, t, resp.Message)
  37.  
    }
  38.  
    }
  39.  
    }