更不便的在微信公众号阅读文章能够关注公众号:海生的go花园
一、介绍
在第五章,咱们学习了.pb.go文件
《go入门grpc》第五章:protoc生成的.pb.go文件解读
本章咱们学习下protoc --go-grpc_out
命令生成的_grpc.pb.go文件。
咱们以hello.proto文件为例,代码如下:
syntax = "proto3";package hello;import "google/protobuf/timestamp.proto";option go_package = "github/hisheng/grpc-demo1/api";service Say { rpc SayHello (HelloRequest) returns (HelloReply) {}}message HelloRequest { string name = 1;}message HelloReply { string message = 1; google.protobuf.Timestamp last_updated = 2;}
应用protoc --go-grpc_out
命令生成了 hello_grpc.pb.go文件。
package api......type SayClient interface { SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)}......type SayServer interface { SayHello(context.Context, *HelloRequest) (*HelloReply, error) mustEmbedUnimplementedSayServer()}......
次要有三局部
- package
- Server服务端接口,以及实现
- Client客户端接口,以及实现
二、Server服务端接口,以及实现
三、Client客户端接口,以及实现
SayClient 是 SayService 的 客户端。
次要包含定义了一个SayClient接口,以及一个sayClient构造体。
sayClient构造体实现了SayClient接口。
对外提供一个 NewSayClient()来生成初始化SayClient客户端。
NewSayClient(cc grpc.ClientConnInterface) SayClient
type SayClient interface {
SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)
}
type sayClient struct {
cc grpc.ClientConnInterface
}
func NewSayClient(cc grpc.ClientConnInterface) SayClient {
return &sayClient{cc}
}
func (c sayClient) SayHello(ctx context.Context, in HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) {
out := new(HelloReply)err := c.cc.Invoke(ctx, "/hello.Say/SayHello", in, out, opts...)if err != nil { return nil, err}return out, nil
}