Skip to content

Instantly share code, notes, and snippets.

@kevinmichaelchen
Last active November 30, 2017 00:02
Show Gist options
  • Save kevinmichaelchen/385029d2af2650df49be81b48c9f5c3c to your computer and use it in GitHub Desktop.
Save kevinmichaelchen/385029d2af2650df49be81b48c9f5c3c to your computer and use it in GitHub Desktop.
gRPC demo

Step 1

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);
}

Step 2:

You run a Gradle task to auto-generate Java files from your Proto file.

Step 3:

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();
  }
}

Step 4: Implement the client

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.

Considerations

  • Security and authorization can be handled by passing the JWT in the message request.
  • Status codes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment