如何用gRPC将Go语言为?

摘要:gRPC是谷歌推出的一个rpc服务框架, 数据编码采用protobuf实现. 安装环境 go install google.golang.orgprotobufcmdprotoc-gen-go@latest go install go
gRPC是谷歌推出的一个rpc服务框架, 数据编码采用protobuf实现. 安装环境 go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest 缺少可能导致出现可执行程序没有找到的报错, 可以参考stackoverflow的帖子 文件 syntax = "proto3"; option go_package = "./myproto"; package myproto; message Hello { string name = 1; } service HelloService { rpc SayHello (Hello) returns (Hello); } 分别需要message和service2个部分的内容 编译 ./bin/bin/protoc --go_out=. ./myproto/hello.proto ./bin/bin/protoc --go-grpc_out=. ./myproto/hello.proto 使用上述指令编译为符合grpc使用的服务, 一个是message的定义的GO实现, 一个是service的定义的GO实现 根据grpc官方文档应该采用类似以下的指令实现, 效果是一样的 protoc --go_out=. --go_opt=paths=source_relative \ --go-grpc_out=. --go-grpc_opt=paths=source_relative \ ./myproto/hello.proto 本质是编译message和编译rpc的service 使用 以下代码为生成出来的go的grpc的服务的代码 // HelloServiceClient is the client API for HelloService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type HelloServiceClient interface { SayHello(ctx context.Context, in *Hello, opts ...grpc.CallOption) (*Hello, error) } type helloServiceClient struct { cc grpc.ClientConnInterface } func NewHelloServiceClient(cc grpc.ClientConnInterface) HelloServiceClient { return &helloServiceClient{cc} } func (c *helloServiceClient) SayHello(ctx context.Context, in *Hello, opts ...grpc.CallOption) (*Hello, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(Hello) err := c.cc.Invoke(ctx, HelloService_SayHello_FullMethodName, in, out, cOpts...) if err != nil { return nil, err } return out, nil } 这些是自动生成的文件内容 Server // HelloServiceServer is the server API for HelloService service. // All implementations must embed UnimplementedHelloServiceServer // for forward compatibility. type HelloServiceServer interface { SayHello(context.Context, *Hello) (*Hello, error) mustEmbedUnimplementedHelloServiceSe
阅读全文