默认所有变量都是可选的(optional),repeated 则表示数组。主要 service rpc 接口接受单个 message 参数,返回单个 message。
参考官方给出示例,如下所示:
syntax="proto3";packagehelloworld;// The greeting service definition.service Greeter {// Sends a greetingrpcSayHello (HelloRequest) returns (HelloReply) {}}// The request message containing the user's name.message HelloRequest {string name =1;}// The response message containing the greetingsmessage HelloReply {string message =1;}
生成的 Go 文件中客户端相关代码如下,主要和实现了 HelloServiceClient 接口。用户可以通过 gRPC 来直接调用这个接口。
typeGreeterClientinterface {// Sends a greetingSayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error)}typegreeterClientstruct { cc *grpc.ClientConn}funcNewGreeterClient(cc *grpc.ClientConn) GreeterClient {return&greeterClient{cc}}func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { out :=new(HelloReply) err := c.cc.Invoke(ctx, "/helloworld.Greeter/SayHello", in, out, opts...)if err !=nil {returnnil, err }return out, nil}
用户直接调用接口方法:创建连接、创建客户端、调用接口。
packagemainimport ("context""log""os""time""google.golang.org/grpc" pb "hello/hello")const (address="localhost:50051"defaultName="world")funcmain() {// Set up a connection to the server. conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())if err !=nil { log.Fatalf("did not connect: %v", err) }defer conn.Close() c := pb.NewGreeterClient(conn)// Contact the server and print out its response. name := defaultNameiflen(os.Args) >1 { name = os.Args[1] } ctx, cancel := context.WithTimeout(context.Background(), time.Second)defercancel() r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})if err !=nil { log.Fatalf("could not greet: %v", err) } log.Printf("Greeting: %s", r.GetMessage())}