gRPC
gRPC
安装Protocol Buffer 并生成代码
下载安装 protobuf
Protocol Buffer Compiler Installation
$ brew install protobuf
$ protoc --version # Ensure compiler version is 3+
安装 go 插件
$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
export PATH="$PATH:$(go env GOPATH)/bin"
protoc-gen-go --version
protoc-gen-go-grpc --version
生成代码
syntax = "proto3";
package hello.v1;
option go_package = "grpc-module1/proto";
message Person {
string name =1;
}
protoc --go_out=. --go_opt=paths=source_relative proto/hello.proto
go mod tidy
go mod vendor
生成包含服务的代码
syntax = "proto3";
package hello;
option go_package="grpc-module2/proto";
service HelloService {
rpc SayHello(SayHelloRequest) returns (SayHelloResponse);
}
message SayHelloRequest {
string name = 1;
}
message SayHelloResponse {
string message =1;
}
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative hello.proto
go mod tidy
go mod vendor
命令行访问服务器
grpcurl -d '{"name":"Chris"}' \
-import-path ./proto -proto hello.proto \
-plaintext localhost:50051 \
hello.HelloService/SayHello