Tags:conceptgrpcRemoteProcedureCalls Status:🟩
Google Remote Procedure Call (gRPC)
Summary
A modern framework that uses HTTP/2 for transport, allowing for faster binary communication. It supports synchronous and asynchronous calls, can handle streaming data, and employs Protocol Buffers for message serialization. Additionally, it accommodates multiple types of communication, including Unary, Server/Client Streaming, and Bidirectional.
Details
Simple RPC (unary) The client sends a request to the server using the stub and waits for a response to come back, just like a normal function call.
rpc SayHello(HelloRequest) returns (HelloResponse);Server-side streaming RPC
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. As you can see in our example, you specify a server-side streaming method by placing the stream keyword before the response type.
rpc LotsOfReplies(HelloRequest) returns (stream HelloResponse);Client-side streaming RPC
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 all and return its response. You specify a client-side streaming method by placing the stream keyword before the request type.
rpc LotsOfGreetings(stream HelloRequest) returns (HelloResponse);Bidirectional streaming RPC
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. You specify this type of method by placing the stream keyword before both the request and the response.
rpc BidiHello(stream HelloRequest) returns (stream HelloResponse);Wire Types
| ID | Name | Used For |
|---|---|---|
| 0 | VARINT | int32, int64, uint32, uint64, sint32, sint64, bool, enum |
| 1 | I64 | fixed64, sfixed64, double |
| 2 | LEN | string, bytes, embedded messages, packed repeated fields |
| 3 | SGROUP | group start (deprecated) |
| 4 | EGROUP | group end (deprecated) |
| 5 | I32 | fixed32, sfixed32, float |
Example
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (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;
}