GO中使用gRPC通信
目录
安装
安装Protocol Buffer编译器
从Protocol Buffer的Github主页下载编译器,并加入到PATH中
安装GO插件
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
编写gRPC定义文件
syntax = "proto3";
option go_package = "google.golang.org/grpc/examples/helloworld/helloworld";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
生成gRPC代码
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative hello.proto
执行该命令会生成hello.pb.go
和hello_grpc.pb.go
两个文件:
hello.pb.go
,用于填充,序列化以及获取HelloRequest
和HelloReply
消息类型hello_grpc.pb.go
,生成的客户端和服务端代码