grpc 入門(二)– 服務介面型別

王的部落格發表於2018-05-30

本節是繼上一章節 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

 

   

 

相關文章