gRPC
- is a high-performance, open-source remote procedure call (RPC) framework
- originally developed by Google
- it lets services call methods on other services as if they were local functions with their parameters and return types — even when they’re running on different machines
- uses protocol buffers to describe both the service interface and the structure of the payload messages
- supports load balancing, tracing, health checking and authentication
- operates over HTTP 2.0
gRPC - Allowed RPC Types
with their parameters and return types
|
Unary RPC |
|
|
Server Streaming RPC |
|
|
Client Streaming RPC |
|
|
Bi-Directional Streaming RPC |
|
gRPC - Example
Defining a Service
example service defined as a protocol buffer file:
// proto version 3
syntax = "proto3";
// A service definition with 2 RPCs
service HelloService {
rpc SayHello (HelloRequest) returns (HelloResponse); // Unary RPC
rpc BidiHello (stream HelloRequest) returns (stream HelloResponse); // Bi-directional RPC
}
message HelloRequest {
string greeting = 1; // tag/field number 1 (should never change for backward compatibility)
}
message HelloResponse {
string reply = 1;
}
the file above defines a Service with 2 RPCs:
- SayHello RPC - takes in a single message and returns a single message
- BidiHello RPC - takes in a stream of messages and returns a stream of messages
Generating Client & Server Code
protoc - is compiler that takes a .proto file and outputs code in the specified language
- if you haven’t installed the compiler, download the package and follow the instructions in the README
- further instructions now depends on the target language
Let’s use protoc to compile the hello-service.proto file and auto generate Go files:
protoc \
--go_out=. \
--go_opt=paths=source_relative \
--go-grpc_out=.
--go-grpc_opt=paths=source_relative \
hello-service.proto
where:
—go_out=.- enables the Go Protobuf plugin—go_opt=paths=source_relative- controls where the generated Protobuf message files are placed (i.e.hello-service.pb.go).source_relativemeans output files go next to the.protofile—go-grpc_out=.- enables the Go gRPC plugin—go-grpc_opt=paths=source_relative- controls where the generated gRPC client & server code are placed (i.e.hello-service_grpc.pb.go)
gRPC - Implementations
- Java gRPC - https://grpc.io/docs/tutorials/basic/java/
- using plugin
protoc-gen-grpc-java- install plugin: https://github.com/grpc/grpc-java/tree/master/compiler
- run command
protoc --plugin=protoc-gen-grpc-java --grpc-java_out="$OUTPUT_FILE" --proto_path="$DIR_OF_PROTO_FILE" "$PROTO_FILE"
- use maven for java - https://github.com/grpc/grpc-java
- using plugin
- SpringBoot gRPC Wrapper - https://github.com/LogNet/grpc-spring-boot-starter