gRPC
gRPC is a high-performance communication protocol based on HTTP/2 and protocol buffers. Its main benefits over using HTTP with JSON are:
- Protocol buffers are binary, high-performance serialization mechanism. Depending on implementation, it can be 8x faster and message size can be around 60% - 80% smaller
- Contract between service and client is explicit (by using
proto
files)
gRPC implementation in e-shop
In this current implementation, the communication between API Gateway and microservices leverages the usage of gRPC. gRPC is language agnostic: all services are defined using proto
files. These files are based on the protobuffer language and can be found in the shared library grpc
under libs/grpc/src/main/proto
. Here is an example of a proto
file:
syntax = "proto3";
package eshop.userService.grpc;
option java_multiple_files = true;
option java_package = "eshop.userService.grpc";
option java_outer_classname = "UserServiceProto";
service UserService {
rpc getUserById(GetUserByIdRequest) returns (User) {}
}
message User {
string id = 1;
string email = 2;
string username = 3;
}
message GetUserByIdRequest {
string productId = 1;
}
Creating gRPC server
Each microservice is a gRPC server, which leverages grpc-server-spring-boot-starter to setup a gRPC server. In order to implement the endpoint, you need to annotate the service with GRPCService
and implements the interface, which was auto-generated by the starter. Here's an example of a gRPC server in this application
@GrpcService
@RequiredArgsConstructor
public class InventoryServiceProtoServiceImpl extends InventoryServiceGrpc.InventoryServiceImplBase {
@Override
public void getInventoryByProductId(GetInventoryByProductIdRequest request,
StreamObserver<Inventory> responseObserver) {
// Your application code...
}
}
Creating gRPC client
gRPC is language agnostic, though gRPC servers are implemented with Java
, the clients can be implemented by any other programming language. In this case, the client is written in API gateway
with Javascript/Node.js. This project uses Buf to auto generate typescript
types from proto
definition files. It ensures that the client is fully type-safe.