S1:|在go中玩下gRPC

gRPC很常见, 也很常用, 来玩下。
先安装该安装的, 比如protoc, protoc-gen-go, grpc, 该设置的环境变量设置一下,这些很简单, 不必多说。

写协议文件data.proto:

syntax = "proto3"; package example; service TaogeApi { rpc MyFun(ReqBody) returns (RspBody){} }message ReqBody { int32cmd = 1; string str = 2; }message RspBody { int32cmd= 1; int32code = 2; string str= 3; }

写服务端代码s.go
package main import ( "example" "net" "google.golang.org/grpc" "google.golang.org/grpc/reflection" "golang.org/x/net/context" "log" )const ( HOST string = "localhost" PORT string = "8080" )type Haha struct{} func (fd *Haha) MyFun(ctx context.Context, in *example.ReqBody) (out *example.RspBody, err error) { log.Println("Cmd is ", in.Cmd) log.Println("Str is ", in.Str)out = &example.RspBody{Cmd:in.Cmd, Code:10086, Str:"heheda"} return out, nil }func main() { listener, err := net.Listen("tcp", HOST + ":" + PORT) if err != nil { log.Fatalln("failed to listen at: " + HOST + ":" + PORT) } else { log.Println("server is listening at: " + HOST + ":" + PORT) }rpcServer := grpc.NewServer() example.RegisterTaogeApiServer(rpcServer, &Haha{}) reflection.Register(rpcServer)if err = rpcServer.Serve(listener); err != nil { log.Fatalln("failed to serve at: " + HOST + ":" + PORT) } }

让服务端跑起来。
写客户端代码c.go:
package main import ( "google.golang.org/grpc" "log" "example" "golang.org/x/net/context" )const ( ADDRESS string = "localhost:8080" )func main() { conn, err := grpc.Dial(ADDRESS, grpc.WithInsecure()) if err != nil { log.Fatalln("failed to connect: " + ADDRESS) } defer conn.Close()client := example.NewTaogeApiClient(conn) rsp,err := client.MyFun(context.Background(), &example.ReqBody{Cmd:110, Str:"hehe"}) if err != nil { log.Fatalln("MyFun error:" + err.Error()) }log.Println("Cmd is ", rsp.Cmd) log.Println("Code is ", rsp.Code) log.Println("Str is ", rsp.Str) }

也跑起来。

客户端log为:
2018/09/21 22:12:17 Cmd is110 2018/09/21 22:12:17 Code is10086 2018/09/21 22:12:17 Str isheheda


有个地方要注意, 在data.proto文件中,变量是小写的, 但protoc和protoc-gen-go转换成为大写的(联想go的特性,想想为什么?),而且连下划线也转啊,有兴趣的可以试试。 我之前也说过一次(那一次是把大写转化为小写的了)。
不多说。

【S1:|在go中玩下gRPC】



    推荐阅读