gRPC Basics - Java

This tutorial provides a basic Java programmer’s introduction toworking with gRPC.

By walking through this example you’ll learn how to:

  • Define a service in a .proto file.
  • Generate server and client code using the protocol buffer compiler.
  • Use the Java gRPC API to write a simple client and server for your service.

It assumes that you have read theOverview and are familiarwithprotocolbuffers. Notethat the example in this tutorial uses theproto3 version of the protocolbuffers language: you can find out more in theproto3 languageguide andJavagenerated codeguide.

Why use gRPC?

Our example is a simple route mapping application that lets clients getinformation about features on their route, create a summary of their route, andexchange route information such as traffic updates with the server and otherclients.

With gRPC we can define our service once in a .proto file and implement clientsand servers in any of gRPC’s supported languages, which in turn can be run inenvironments ranging from servers inside Google to your own tablet - all thecomplexity of communication between different languages and environments ishandled for you by gRPC. We also get all the advantages of working with protocolbuffers, including efficient serialization, a simple IDL, and easy interfaceupdating.

Example code and setup

The example code for our tutorial is ingrpc/grpc-java/examples/src/main/java/io/grpc/examples/routeguide.To download the example, clone the latest release in grpc-java repository byrunning the following command:

  1. $ git clone -b v1.28.1 https://github.com/grpc/grpc-java.git

Then change your current directory to grpc-java/examples:

  1. $ cd grpc-java/examples/routeguide

Defining the service

Our first step (as you’ll know from theOverview) is todefine the gRPC service and the method request and response types usingprotocolbuffers. You cansee the complete .proto file ingrpc-java/examples/src/main/proto/route_guide.proto.

As we’re generating Java code in this example, we’ve specified a java_packagefile option in our .proto:

  1. option java_package = "io.grpc.examples.routeguide";

This specifies the package we want to use for our generated Java classes. If noexplicit java_package option is given in the .proto file, then by default theproto package (specified using the “package” keyword) will be used. However,proto packages generally do not make good Java packages since proto packages arenot expected to start with reverse domain names. If we generate code in anotherlanguage from this .proto, the java_package option has no effect.

To define a service, we specify a named service in the .proto file:

  1. service RouteGuide {
  2. ...
  3. }

Then we define rpc methods inside our service definition, specifying theirrequest and response types. gRPC lets you define four kinds of service methods,all of which are used in the RouteGuide service:

  • A simple RPC where the client sends a request to the server using the stuband waits for a response to come back, just like a normal function call.
  1. // Obtains the feature at a given position.
  2. rpc GetFeature(Point) returns (Feature) {}
  • A server-side streaming RPC where the client sends a request to the serverand gets a stream to read a sequence of messages back. The client reads fromthe returned stream until there are no more messages. As you can see in ourexample, you specify a server-side streaming method by placing the streamkeyword before the response type.
  1. // Obtains the Features available within the given Rectangle. Results are
  2. // streamed rather than returned at once (e.g. in a response message with a
  3. // repeated field), as the rectangle may cover a large area and contain a
  4. // huge number of features.
  5. rpc ListFeatures(Rectangle) returns (stream Feature) {}
  • A client-side streaming RPC where the client writes a sequence of messagesand sends them to the server, again using a provided stream. Once the clienthas finished writing the messages, it waits for the server to read them alland return its response. You specify a client-side streaming method by placingthe stream keyword before the request type.
  1. // Accepts a stream of Points on a route being traversed, returning a
  2. // RouteSummary when traversal is completed.
  3. rpc RecordRoute(stream Point) returns (RouteSummary) {}
  • A bidirectional streaming RPC where both sides send a sequence of messagesusing a read-write stream. The two streams operate independently, so clientsand servers can read and write in whatever order they like: for example, theserver could wait to receive all the client messages before writing itsresponses, or it could alternately read a message then write a message, orsome other combination of reads and writes. The order of messages in eachstream is preserved. You specify this type of method by placing the streamkeyword before both the request and the response.
  1. // Accepts a stream of RouteNotes sent while a route is being traversed,
  2. // while receiving other RouteNotes (e.g. from other users).
  3. rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}

Our .proto file also contains protocol buffer message type definitions for allthe request and response types used in our service methods - for example, here’sthe Point message type:

  1. // Points are represented as latitude-longitude pairs in the E7 representation
  2. // (degrees multiplied by 10**7 and rounded to the nearest integer).
  3. // Latitudes should be in the range +/- 90 degrees and longitude should be in
  4. // the range +/- 180 degrees (inclusive).
  5. message Point {
  6. int32 latitude = 1;
  7. int32 longitude = 2;
  8. }

Generating client and server code

Next we need to generate the gRPC client and server interfaces from our .protoservice definition. We do this using the protocol buffer compiler protoc witha special gRPC Java plugin. You need to use theproto3 compiler (which supportsboth proto2 and proto3 syntax) in order to generate gRPC services.

When using Gradle or Maven, the protoc build plugin can generate the necessarycode as part of the build. You can refer to thegrpc-java README forhow to generate code from your own .proto files.

The following classes are generated from our service definition:

  • Feature.java, Point.java, Rectangle.java, and others which contain allthe protocol buffer code to populate, serialize, and retrieve our request andresponse message types.
  • RouteGuideGrpc.java which contains (along with some other useful code):
    • a base class for RouteGuide servers to implement,RouteGuideGrpc.RouteGuideImplBase, with all the methods defined in theRouteGuide service.
    • stub classes that clients can use to talk to a RouteGuide server.

Creating the server

First let’s look at how we create a RouteGuide server. If you’re onlyinterested in creating gRPC clients, you can skip this section and go straighttoCreating the client (though you might find it interestinganyway!).

There are two parts to making our RouteGuide service do its job:

  • Overriding the service base class generated from our service definition: doingthe actual “work” of our service.
  • Running a gRPC server to listen for requests from clients and return theservice responses.

You can find our example RouteGuide server ingrpc-java/examples/src/main/java/io/grpc/examples/routeguide/RouteGuideServer.java.Let’s take a closer look at how it works.

Implementing RouteGuide

As you can see, our server has a RouteGuideService class that extends thegenerated RouteGuideGrpc.RouteGuideImplBase abstract class:

  1. private static class RouteGuideService extends RouteGuideGrpc.RouteGuideImplBase {
  2. ...
  3. }

Simple RPC

RouteGuideService implements all our service methods. Let’slook at the simplest method first, GetFeature(), which just gets a Point fromthe client and returns the corresponding feature information from its databasein a Feature.

  1. @Override
  2. public void getFeature(Point request, StreamObserver<Feature> responseObserver) {
  3. responseObserver.onNext(checkFeature(request));
  4. responseObserver.onCompleted();
  5. }
  6. ...
  7. private Feature checkFeature(Point location) {
  8. for (Feature feature : features) {
  9. if (feature.getLocation().getLatitude() == location.getLatitude()
  10. && feature.getLocation().getLongitude() == location.getLongitude()) {
  11. return feature;
  12. }
  13. }
  14. // No feature was found, return an unnamed feature.
  15. return Feature.newBuilder().setName("").setLocation(location).build();
  16. }

The getFeature() method takes two parameters:

  • Point: the request
  • StreamObserver<Feature>: a response observer, which is a special interfacefor the server to call with its response.

To return our response to the client and complete the call:

  • We construct and populate a Feature response object to return to theclient, as specified in our service definition. In this example, we do thisin a separate private checkFeature() method.
  • We use the response observer’s onNext() method to return the Feature.
  • We use the response observer’s onCompleted() method to specify that we’vefinished dealing with the RPC.

Server-side streaming RPC

Next let’s look at one of our streaming RPCs. ListFeatures is a server-sidestreaming RPC, so we need to send back multiple Features to our client.

  1. private final Collection<Feature> features;
  2. ...
  3. @Override
  4. public void listFeatures(Rectangle request, StreamObserver<Feature> responseObserver) {
  5. int left = min(request.getLo().getLongitude(), request.getHi().getLongitude());
  6. int right = max(request.getLo().getLongitude(), request.getHi().getLongitude());
  7. int top = max(request.getLo().getLatitude(), request.getHi().getLatitude());
  8. int bottom = min(request.getLo().getLatitude(), request.getHi().getLatitude());
  9. for (Feature feature : features) {
  10. if (!RouteGuideUtil.exists(feature)) {
  11. continue;
  12. }
  13. int lat = feature.getLocation().getLatitude();
  14. int lon = feature.getLocation().getLongitude();
  15. if (lon >= left && lon <= right && lat >= bottom && lat <= top) {
  16. responseObserver.onNext(feature);
  17. }
  18. }
  19. responseObserver.onCompleted();
  20. }

Like the simple RPC, this method gets a request object (the Rectangle in whichour client wants to find Features) and a StreamObserver response observer.

This time, we get as many Feature objects as we need to return to the client(in this case, we select them from the service’s feature collection based onwhether they’re inside our request Rectangle), and write them each in turn tothe response observer using its onNext() method. Finally, as in our simpleRPC, we use the response observer’s onCompleted() method to tell gRPC thatwe’ve finished writing responses.

Client-side streaming RPC

Now let’s look at something a little more complicated: the client-side streamingmethod RecordRoute(), where we get a stream of Points from the client andreturn a single RouteSummary with information about their trip.

  1. @Override
  2. public StreamObserver<Point> recordRoute(final StreamObserver<RouteSummary> responseObserver) {
  3. return new StreamObserver<Point>() {
  4. int pointCount;
  5. int featureCount;
  6. int distance;
  7. Point previous;
  8. long startTime = System.nanoTime();
  9. @Override
  10. public void onNext(Point point) {
  11. pointCount++;
  12. if (RouteGuideUtil.exists(checkFeature(point))) {
  13. featureCount++;
  14. }
  15. // For each point after the first, add the incremental distance from the previous point
  16. // to the total distance value.
  17. if (previous != null) {
  18. distance += calcDistance(previous, point);
  19. }
  20. previous = point;
  21. }
  22. @Override
  23. public void onError(Throwable t) {
  24. logger.log(Level.WARNING, "Encountered error in recordRoute", t);
  25. }
  26. @Override
  27. public void onCompleted() {
  28. long seconds = NANOSECONDS.toSeconds(System.nanoTime() - startTime);
  29. responseObserver.onNext(RouteSummary.newBuilder().setPointCount(pointCount)
  30. .setFeatureCount(featureCount).setDistance(distance)
  31. .setElapsedTime((int) seconds).build());
  32. responseObserver.onCompleted();
  33. }
  34. };
  35. }

As you can see, like the previous method types our method gets aStreamObserver response observer parameter, but this time it returns aStreamObserver for the client to write its Points.

In the method body we instantiate an anonymous StreamObserver to return, inwhich we:

  • Override the onNext() method to get features and other information each timethe client writes a Point to the message stream.
  • Override the onCompleted() method (called when the client has finishedwriting messages) to populate and build our RouteSummary. We then call ourmethod’s own response observer’s onNext() with our RouteSummary, and thencall its onCompleted() method to finish the call from the server side.

Bidirectional streaming RPC

Finally, let’s look at our bidirectional streaming RPC RouteChat().

  1. @Override
  2. public StreamObserver<RouteNote> routeChat(final StreamObserver<RouteNote> responseObserver) {
  3. return new StreamObserver<RouteNote>() {
  4. @Override
  5. public void onNext(RouteNote note) {
  6. List<RouteNote> notes = getOrCreateNotes(note.getLocation());
  7. // Respond with all previous notes at this location.
  8. for (RouteNote prevNote : notes.toArray(new RouteNote[0])) {
  9. responseObserver.onNext(prevNote);
  10. }
  11. // Now add the new note to the list
  12. notes.add(note);
  13. }
  14. @Override
  15. public void onError(Throwable t) {
  16. logger.log(Level.WARNING, "Encountered error in routeChat", t);
  17. }
  18. @Override
  19. public void onCompleted() {
  20. responseObserver.onCompleted();
  21. }
  22. };
  23. }

As with our client-side streaming example, we both get and return aStreamObserver response observer, except this time we return values via ourmethod’s response observer while the client is still writing messages to _their_message stream. The syntax for reading and writing here is exactly the same asfor our client-streaming and server-streaming methods. Although each side willalways get the other’s messages in the order they were written, both the clientand server can read and write in any order — the streams operate completelyindependently.

Starting the server

Once we’ve implemented all our methods, we also need to start up a gRPC serverso that clients can actually use our service. The following snippet shows how wedo this for our RouteGuide service:

  1. public RouteGuideServer(int port, URL featureFile) throws IOException {
  2. this(ServerBuilder.forPort(port), port, RouteGuideUtil.parseFeatures(featureFile));
  3. }
  4. /** Create a RouteGuide server using serverBuilder as a base and features as data. */
  5. public RouteGuideServer(ServerBuilder<?> serverBuilder, int port, Collection<Feature> features) {
  6. this.port = port;
  7. server = serverBuilder.addService(new RouteGuideService(features))
  8. .build();
  9. }
  10. ...
  11. public void start() throws IOException {
  12. server.start();
  13. logger.info("Server started, listening on " + port);
  14. ...
  15. }

As you can see, we build and start our server using a ServerBuilder.

To do this, we:

  • Specify the address and port we want to use to listen for client requestsusing the builder’s forPort() method.
  • Create an instance of our service implementation class RouteGuideServiceand pass it to the builder’s addService() method.
  • Call build() and start() on the builder to create and start an RPC serverfor our service.

Creating the client

In this section, we’ll look at creating a client for our RouteGuideservice. You can see our complete example client code ingrpc-java/examples/src/main/java/io/grpc/examples/routeguide/RouteGuideClient.java.

Instantiating a stub

To call service methods, we first need to create a stub, or rather, two stubs:

  • a blocking/synchronous stub: this means that the RPC call waits for theserver to respond, and will either return a response or raise an exception.
  • a non-blocking/asynchronous stub that makes non-blocking calls to theserver, where the response is returned asynchronously. You can make certaintypes of streaming call only using the asynchronous stub.

First we need to create a gRPC channel for our stub, specifying the serveraddress and port we want to connect to:

  1. public RouteGuideClient(String host, int port) {
  2. this(ManagedChannelBuilder.forAddress(host, port).usePlaintext());
  3. }
  4. /** Construct client for accessing RouteGuide server using the existing channel. */
  5. public RouteGuideClient(ManagedChannelBuilder<?> channelBuilder) {
  6. channel = channelBuilder.build();
  7. blockingStub = RouteGuideGrpc.newBlockingStub(channel);
  8. asyncStub = RouteGuideGrpc.newStub(channel);
  9. }

We use a ManagedChannelBuilder to create the channel.

Now we can use the channel to create our stubs using the newStub andnewBlockingStub methods provided in the RouteGuideGrpc class we generatedfrom our .proto.

  1. blockingStub = RouteGuideGrpc.newBlockingStub(channel);
  2. asyncStub = RouteGuideGrpc.newStub(channel);

Calling service methods

Now let’s look at how we call our service methods.

Simple RPC

Calling the simple RPC GetFeature on the blocking stub is as straightforwardas calling a local method.

  1. Point request = Point.newBuilder().setLatitude(lat).setLongitude(lon).build();
  2. Feature feature;
  3. try {
  4. feature = blockingStub.getFeature(request);
  5. } catch (StatusRuntimeException e) {
  6. logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
  7. return;
  8. }

We create and populate a request protocol buffer object (in our case Point),pass it to the getFeature() method on our blocking stub, and get back aFeature.

If an error occurs, it is encoded as a Status, which we can obtain from theStatusRuntimeException.

Server-side streaming RPC

Next, let’s look at a server-side streaming call to ListFeatures, whichreturns a stream of geographical Features:

  1. Rectangle request =
  2. Rectangle.newBuilder()
  3. .setLo(Point.newBuilder().setLatitude(lowLat).setLongitude(lowLon).build())
  4. .setHi(Point.newBuilder().setLatitude(hiLat).setLongitude(hiLon).build()).build();
  5. Iterator<Feature> features;
  6. try {
  7. features = blockingStub.listFeatures(request);
  8. } catch (StatusRuntimeException ex) {
  9. logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
  10. return;
  11. }

As you can see, it’s very similar to the simple RPC we just looked at, exceptinstead of returning a single Feature, the method returns an Iterator thatthe client can use to read all the returned Features.

Client-side streaming RPC

Now for something a little more complicated: the client-side streaming methodRecordRoute, where we send a stream of Points to the server and get back asingle RouteSummary. For this method we need to use the asynchronous stub. Ifyou’ve already readCreating the server some of this may look veryfamiliar - asynchronous streaming RPCs are implemented in a similar way on bothsides.

  1. public void recordRoute(List<Feature> features, int numPoints) throws InterruptedException {
  2. info("*** RecordRoute");
  3. final CountDownLatch finishLatch = new CountDownLatch(1);
  4. StreamObserver<RouteSummary> responseObserver = new StreamObserver<RouteSummary>() {
  5. @Override
  6. public void onNext(RouteSummary summary) {
  7. info("Finished trip with {0} points. Passed {1} features. "
  8. + "Travelled {2} meters. It took {3} seconds.", summary.getPointCount(),
  9. summary.getFeatureCount(), summary.getDistance(), summary.getElapsedTime());
  10. }
  11. @Override
  12. public void onError(Throwable t) {
  13. Status status = Status.fromThrowable(t);
  14. logger.log(Level.WARNING, "RecordRoute Failed: {0}", status);
  15. finishLatch.countDown();
  16. }
  17. @Override
  18. public void onCompleted() {
  19. info("Finished RecordRoute");
  20. finishLatch.countDown();
  21. }
  22. };
  23. StreamObserver<Point> requestObserver = asyncStub.recordRoute(responseObserver);
  24. try {
  25. // Send numPoints points randomly selected from the features list.
  26. Random rand = new Random();
  27. for (int i = 0; i < numPoints; ++i) {
  28. int index = rand.nextInt(features.size());
  29. Point point = features.get(index).getLocation();
  30. info("Visiting point {0}, {1}", RouteGuideUtil.getLatitude(point),
  31. RouteGuideUtil.getLongitude(point));
  32. requestObserver.onNext(point);
  33. // Sleep for a bit before sending the next one.
  34. Thread.sleep(rand.nextInt(1000) + 500);
  35. if (finishLatch.getCount() == 0) {
  36. // RPC completed or errored before we finished sending.
  37. // Sending further requests won't error, but they will just be thrown away.
  38. return;
  39. }
  40. }
  41. } catch (RuntimeException e) {
  42. // Cancel RPC
  43. requestObserver.onError(e);
  44. throw e;
  45. }
  46. // Mark the end of requests
  47. requestObserver.onCompleted();
  48. // Receiving happens asynchronously
  49. finishLatch.await(1, TimeUnit.MINUTES);
  50. }

As you can see, to call this method we need to create a StreamObserver, whichimplements a special interface for the server to call with its RouteSummaryresponse. In our StreamObserver we:

  • Override the onNext() method to print out the returned information when theserver writes a RouteSummary to the message stream.
  • Override the onCompleted() method (called when the server has completedthe call on its side) to reduce a CountDownLatch that we can check to see ifthe server has finished writing.

We then pass the StreamObserver to the asynchronous stub’s recordRoute()method and get back our own StreamObserver request observer to write ourPoints to send to the server. Once we’ve finished writing points, we use therequest observer’s onCompleted() method to tell gRPC that we’ve finishedwriting on the client side. Once we’re done, we check our CountDownLatch tocheck that the server has completed on its side.

Bidirectional streaming RPC

Finally, let’s look at our bidirectional streaming RPC RouteChat().

  1. public void routeChat() throws Exception {
  2. info("*** RoutChat");
  3. final CountDownLatch finishLatch = new CountDownLatch(1);
  4. StreamObserver<RouteNote> requestObserver =
  5. asyncStub.routeChat(new StreamObserver<RouteNote>() {
  6. @Override
  7. public void onNext(RouteNote note) {
  8. info("Got message \"{0}\" at {1}, {2}", note.getMessage(), note.getLocation()
  9. .getLatitude(), note.getLocation().getLongitude());
  10. }
  11. @Override
  12. public void onError(Throwable t) {
  13. Status status = Status.fromThrowable(t);
  14. logger.log(Level.WARNING, "RouteChat Failed: {0}", status);
  15. finishLatch.countDown();
  16. }
  17. @Override
  18. public void onCompleted() {
  19. info("Finished RouteChat");
  20. finishLatch.countDown();
  21. }
  22. });
  23. try {
  24. RouteNote[] requests =
  25. {newNote("First message", 0, 0), newNote("Second message", 0, 1),
  26. newNote("Third message", 1, 0), newNote("Fourth message", 1, 1)};
  27. for (RouteNote request : requests) {
  28. info("Sending message \"{0}\" at {1}, {2}", request.getMessage(), request.getLocation()
  29. .getLatitude(), request.getLocation().getLongitude());
  30. requestObserver.onNext(request);
  31. }
  32. } catch (RuntimeException e) {
  33. // Cancel RPC
  34. requestObserver.onError(e);
  35. throw e;
  36. }
  37. // Mark the end of requests
  38. requestObserver.onCompleted();
  39. // Receiving happens asynchronously
  40. finishLatch.await(1, TimeUnit.MINUTES);
  41. }

As with our client-side streaming example, we both get and return aStreamObserver response observer, except this time we send values via ourmethod’s response observer while the server is still writing messages to _their_message stream. The syntax for reading and writing here is exactly the same asfor our client-streaming method. Although each side will always get the other’smessages in the order they were written, both the client and server can read andwrite in any order — the streams operate completely independently.

Try it out!

Follow the instructions in theexample directory README to build and run theclient and server.