本文介绍一些主要的gRPC概念。
服务定义
gRPC支持4种方法:
1、Unary RPCs where the client sends a single request to the server and gets a single response back, just like a normal function call.
入参和返回值是一个普通的protocol buffer message。示例:
message HelloRequest { string greeting = 1; } message HelloResponse { string reply = 1; } service HelloService { rpc SayHello (HelloRequest) returns (HelloResponse); }
2、Server streaming RPCs where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. gRPC guarantees message ordering within an individual RPC call.
入参是一个普通的protocol buffer message,返回值是一个流式的message。示例:
service HelloService { rpc SayHello (HelloRequest) returns (stream HelloResponse); }
3、Client streaming RPCs where the client writes a sequence of messages and sends them to the server, again using a provided stream. Once the client has finished writing the messages, it waits for the server to read them and return its response. Again gRPC guarantees message ordering within an individual RPC call.
入参是一个流式的message,返回值是一个普通的message。示例:
service HelloService { rpc SayHello (stream HelloRequest) returns (HelloResponse); }
4、Bidirectional streaming RPCs where both sides send a sequence of messages using a read-write stream. The two streams operate independently, so clients and servers can read and write in whatever order they like: for example, the server could wait to receive all the client messages before writing its responses, or it could alternately read a message then write a message, or some other combination of reads and writes. The order of messages in each stream is preserved.
入参和返回值都是流式的message。示例:
service HelloService { rpc SayHello (stream HelloRequest) returns (stream HelloResponse); }
同步 VS 异步
同步方法、异步方法都有,根据需要选用。