A High Performance, Open Source Universal RPC
Framework

gRPC is a modern open source high performance Remote Procedure Call (RPC) framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication. It is also applicable in last mile of distributed computing to connect devices, mobile applications and browsers to backend services.

gRPC

Overview

In gRPC, a client application can directly call a method on a server application on a different machine as if it were a local object, making it easier for us to create distributed applications and services. As in many RPC systems, gRPC is based around the idea of defining a service, specifying the methods that can be called remotely with their parameters and return types. On the server side, the server implements this interface and runs a gRPC server to handle client calls. On the client side, the client has a stub (referred to as just a client in some languages) that provides the same methods as the server.

Concept Diagram

gRPC-clients and servers can run and talk to each other in a variety of environments – from servers inside Google to your own desktop – and can be written in any of gRPC’s supported languages. So, for example, you can easily create a gRPC-server in Java with clients in Go, Python, or Ruby. In addition, the latest Google APIs will have gRPC versions of their interfaces, letting you easily build Google functionality into your applications

Used By

 

Working with Protocol Buffers

By default, gRPC uses Protocol Buffers, Google’s mature open source mechanism for serializing structured data (although it can be used with other data formats such as JSON). Here’s a quick intro to how it works. If you’re already familiar with protocol buffers, feel free to skip ahead to the next section.

The first step when working with protocol buffers is to define the structure for the data you want to serialize in a proto file: this is an ordinary text file with a .proto extension. Protocol buffer data is structured as messages, where each message is a small logical record of information containing a series of name-value pairs called fields. Here’s a simple example:

message Person {
  string name = 1;
  int32 id = 2;
  bool has_ponycopter = 3;
}

Then, once you’ve specified your data structures, you use the protocol buffer compiler protoc to generate data access classes in your preferred language(s) from your proto definition. These provide simple accessors for each field, like name() and set_name(), as well as methods to serialize/parse the whole structure to/from raw bytes. So, for instance, if your chosen language is C++, running the compiler on the example above will generate a class called Person. You can then use this class in your application to populate, serialize, and retrieve Person protocol buffer messages.

Quick start with JAVA

Prerequisites

  • JDK version 7 or higher

Get the example code

The example code is part of the grpc-java repo.

  1. Download the repo as a zip file and unzip it, or clone the repo:

    $ git clone -b v1.60.0 --depth 1 https://github.com/grpc/grpc-java
    
  2. Change to the examples directory:

    $ cd grpc-java/examples
    

Run the example

From the examples directory:

  1. Compile the client and server

    $ ./gradlew installDist
    
  2. Run the server:

    $ ./build/install/examples/bin/hello-world-server
    INFO: Server started, listening on 50051
    
  3. From another terminal, run the client:

    $ ./build/install/examples/bin/hello-world-client
    INFO: Will try to greet world ...
    INFO: Greeting: Hello world
    

Congratulations! You’ve just run a client-server application with gRPC.

Note

Timestamps omitted from the client and server trace output shown in this page.

Update the gRPC service

In this section you’ll update the application by adding an extra server method. The gRPC service is defined using protocol buffers. To learn more about how to define a service in a .proto file see Basics tutorial. For now, all you need to know is that both the server and the client stub have a SayHello() RPC method that takes a HelloRequest parameter from the client and returns a HelloReply from the server, and that the method is defined like this:

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

Open src/main/proto/helloworld.proto and add a new SayHelloAgain() method with the same request and response types as SayHello():

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  // Sends another greeting
  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

Remember to save the file!

Update the app

When you build the example, the build process regenerates GreeterGrpc.java, which contains the generated gRPC client and server classes. This also regenerates classes for populating, serializing, and retrieving our request and response types.

However, you still need to implement and call the new method in the hand-written parts of the example app.

Update the server

In the same directory, open src/main/java/io/grpc/examples/helloworld/HelloWorldServer.java. Implement the new method like this:

private class GreeterImpl extends GreeterGrpc.GreeterImplBase {

  @Override
  public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
  }

  @Override
  public void sayHelloAgain(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello again " + req.getName()).build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
  }
}

Update the client

In the same directory, open src/main/java/io/grpc/examples/helloworld/HelloWorldClient.java. Call the new method like this:

public void greet(String name) {
  logger.info("Will try to greet " + name + " ...");
  HelloRequest request = HelloRequest.newBuilder().setName(name).build();
  HelloReply response;
  try {
    response = blockingStub.sayHello(request);
  } catch (StatusRuntimeException e) {
    logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
    return;
  }
  logger.info("Greeting: " + response.getMessage());
  try {
    response = blockingStub.sayHelloAgain(request);
  } catch (StatusRuntimeException e) {
    logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
    return;
  }
  logger.info("Greeting: " + response.getMessage());
}

Run the updated app

Run the client and server like you did before. Execute the following commands from the examples directory:

  1. Compile the client and server:

    $ ./gradlew installDist
    
  2. Run the server:

    $ ./build/install/examples/bin/hello-world-server
    INFO: Server started, listening on 50051
    
  3. From another terminal, run the client:

    $ ./build/install/examples/bin/hello-world-client
    INFO: Will try to greet world ...
    INFO: Greeting: Hello world
    INFO: Greeting: Hello again world

This contains Package

 
Package Description
io.grpc
The gRPC core public API.
io.grpc.auth
Implementations of CallCredentials and authentication related API.
io.grpc.binarylog.v1  
io.grpc.channelz.v1  
io.grpc.grpclb  
io.grpc.health.v1  
io.grpc.inprocess
The in-process transport which is for when a server is in the same process as the client.
io.grpc.lb.v1  
io.grpc.netty
The main transport implementation based on Netty, for both the client and the server.
io.grpc.okhttp
A lightweight transport based on OkHttp, mainly for use on Android (client-only).
io.grpc.protobuf
API for gRPC over Protocol Buffers, including tools for serializing and de-serializing protobuf messages.
io.grpc.protobuf.lite
API for gRPC over Protocol Buffers with proto message classes generated by the Lite Runtime library.
io.grpc.protobuf.services
Service definitions and utilities with protobuf dependency for the pre-defined gRPC services.
io.grpc.reflection.v1alpha  
io.grpc.services
Service definitions and utilities for the pre-defined gRPC services.
io.grpc.servlet
API that implements gRPC server as a servlet.
io.grpc.servlet.jakarta
API that implements gRPC server as a servlet.
io.grpc.stub
API for the Stub layer.
io.grpc.stub.annotations  
io.grpc.testing
API that is useful for testing gRPC.
io.grpc.util
Utilities with advanced features in the core layer that user can optionally use.
io.grpc.xds
Library for gPRC proxyless service mesh using Envoy xDS protocol.
io.grpc.xds.orca  

1 thought on “gRPC – API Architecture Style Every Developer Must Know”

  1. Pingback: MQTT Message Queuing Telemetry Transport Truly available 23

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top