First, you have to create your .proto
file which is your Interface Description Language (IDL).
syntax = "proto3";
package com.teslagov.clarakm.calculator;
message AddRequest {
int32 a = 1;
int32 b = 2;
}
message AddResponse {
int32 sum = 1;
}
service AddService {
rpc add(AddRequest) returns (AddResponse);
}
You run a Gradle task to auto-generate Java files from your Proto file.
Implement the Service, which is akin to a Spring Controller.
@GRpcService
public class AddService extends AddServiceImplBase {
@Override
public void add(
AddRequest request,
StreamObserver<AddResponse> responseObserver)
{
int a = request.getA();
int b = request.getB();
// stream in the response
responseObserver.onNext(AddResponse.newBuilder().setSum(a + b).build());
// signal the end of RPC
responseObserver.onCompleted();
}
}
public class GrpcClient {
public int add(int a, int b) {
// Use a Spring Bean to make the Channel a singleton
// The Channel can be heavily re-used so you only need one
Channel channel = ManagedChannelBuilder.forAddress( "127.0.0.1", 6565 )
.usePlaintext( true )
.build();
AddServiceBlockingStub stub = AddServiceGrpc.newBlockingStub(channel);
AddRequest request = AddRequest.newBuilder().setA(a).setB(b).build();
AddResponse response = stub.add(request);
return response.getSum();
}
}
This is a bit simpler than making a HTTP request, streaming the response into a string, and deserializing the string into an object.
- Security and authorization can be handled by passing the JWT in the message request.
- Status codes.