本節是繼上一章節 Hello world 的進一步深入挖掘;
一、grpc服務接口類型
在godoc的網站上對grpc的端口類型進行了簡單的介紹,總共有下面4種類型[1]:
gRPC lets you define four kinds of service method:
Unary RPCs where the client sends a single request to the server and gets a single response back, just like a normal function call.
rpc SayHello(HelloRequest) returns (HelloResponse){
}
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.
rpc LotsOfReplies(HelloRequest) returns (stream HelloResponse){
}
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.
rpc LotsOfGreetings(stream HelloRequest) returns (HelloResponse) {
}
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.
rpc BidiHello(stream HelloRequest) returns (stream HelloResponse){
}
We’ll look at the different types of RPC in more detail in the RPC life cycle section below.
上面是從官網摘抄過來的,簡單的來講客戶端和服務發送數據有兩種形式:Unary和Streaming。Unary (一元)一次只發送一個包; Streaming(流)一次可以發送多個包。兩種方式組合一下就形成了4種類型:
| 服務端 | 客戶端 | |
| 1 | Unary | Unary |
| 2 | Streaming | Streaming |
| 3 | Unary | Streaming |
| 4 | Streaming | Unary |
在上一篇Hello world文章里面的示例就是第一種類型接口,它最終聲明了一個需要開發者去實習具體業務邏輯的接口:
// Server API for Greeter service type GreeterServer interface { // Sends a greeting SayHello(context.Context, *HelloRequest) (*HelloReply, error) }
開發者需要根據業務需求來考慮使用不同的grpc服務接口類型 。
參考網址
[1] https://grpc.io/docs/guides/concepts.html#service-definition
