先决条件
- Go
- Protocol buffer compiler, protoc, version 3 https://github.com/protocolbuffers/protobuf/releases/tag/v25.0
- Go plugins for protocol compiler
- `go install google.golang.org/protobuf/cmd/[email protected]`
- `go install google.golang.org/grpc/cmd/[email protected]`
运行实例
- `git clone -b v1.58.2 --depth 1 https://github.com/grpc/grpc-go`
- `cd grpc-go/examples/helloworld`
- `go run greeter_server/main.go`
- `go run greeter_client/main.go`
更新 gRPC service
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
// Sends another greeting
rpc SayHelloAgain (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 \
helloworld/helloworld.proto
更新 server
func (s *server) SayHelloAgain(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
return &pb.HelloReply{Message: "Hello again " + in.GetName()}, nil
}
更新 client
r, err = c.SayHelloAgain(ctx, &pb.HelloRequest{Name: *name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.GetMessage())