This post expands on our previous blog on generating gRPC code with Maven, and explains how to use the generated api jar to implement a gRPC service and client. This example uses the StackLeader dockerized karaf container to illustrate running the service and connecting to the service with the client. This is largely done to simplify the process of running the example.
Source Code
The source code for this example is available on github.
Project Structure
Implementing the Service
To implement the service, we need to extend the generated GreeterGrpc.AbstractGreeter class.
GreeterService.java
Implementing the Server and Registering our Service Implementation
To expose our service implementation, a gRPC server endpoint needs to be constructed. In this case, we have registered our service implementation as an implementation of the gRPC BindableService interface, and as a result we can easily inject this implementation into our Server class for registration. Additionally, we have registered our HelloWorldServer class as implementing an empty GrpcServer interface in order to provide a lifecycle hook for our service client (i.e. we want our client implementation to wait for the server before it tries to make a connection).
HelloWorldServer.java
Implementing the Client
In order to implement a gRPC client, we need to create an instance of one of the stub classes implementing the GreeterBlockingClient class or the GreeterFutureClient class. For this example, we have chosen to instantiate a GreeterGrpc.GreeterBlockingStub instance. As mentioned above, in order to ensure the gRPC server has been started, we inject the GrpcServer service into our HelloWorldClient component. After the gRPC Server is injected we make a connection to the server and invoke the sayHello method.
HelloWorldClient.java
Running the example in the StackLeader Karaf container
For convenience, we have made available an open source Docker container that will be used in the Karaf blog posts.