Make writing a habit together! This is the fifth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

Some foreign companies, including Netflix, Google, Square and others have adopted gRPC, while domestic bytedance, Meituan and Alibaba have also adopted gRPC communication in many business lines. This article is an introduction to gRPC.

What is a REST API

REST is an architectural style for designing Web-based apis, known as REST APIS. When clients and servers communicate using the restapi, they will have a predefined endpoint and payload contract. REST apis use all HTTP methods, such as GET, PATCH, PUT, POST, and DELETE.

What is RPC?

Remote Procedure Call (RPC) is a request-response protocol. The RPC API uses only the HTTP GET and POST methods. Client-server communication is achieved through server-side interfaces and client-side stubs.

What is the gRPC

gRPC is a modern, open source remote procedure call (RPC) framework that can run anywhere. It enables client and server applications to communicate transparently, and makes it easier to build connected systems. – From gRPC docs.

The reference comes from the gRPC documentation, which roughly means that gRPC is a modern open source remote procedure call (RPC) framework that runs anywhere. It enables client and server applications to communicate transparently and makes it easier to build connected systems.

The framework was developed by Google. Like other RPC systems, gRPC also defines an interface that defines all the methods that clients can access. By default, gRPC uses protocol buffering as an interface definition language and data exchange format. It also supports other data interchange formats, such as JSON.

The IDL in gRPC is defined in a file with an extension. Paul. We can define a version in these files and maintain different versions of the same API in optional different languages.

The different types of RPC supported by gRPC include:

  • Unary- Sends a single request from the client and a single response from the server.
  • Server Streaming- Send a request from the client and then send a series of messages back from the Server.
  • Client Streaming – Sends a series of messages from the Client to the server and the server responds with a message.
  • Bidirectional Streaming – The place where clients and servers send message flows to each other.

Is it better than REST?

Communication like the REST API is possible in A gRPC that uses unary operations, but when it comes to streams, gRPC allows full-duplex streams and uses static paths to communicate, which eliminates delays in path resolution and query parameter increment. As a result, it performs better than REST apis.

Server-side implementation

In this example, we use Java gRPC for one-to-one (Unary) communication.

Start by creating a simple Java application using Maven and add the following dependencies to Maven.

<dependencies> <! -- https://mvnrepository.com/artifact/io.grpc/grpc-netty-shaded --> <dependency> <groupId>io.grpc</groupId> < artifactId > GRPC netty - shaded < / artifactId > < version > 1.45.0 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/io.grpc/grpc-protobuf --> <dependency> <groupId>io.grpc</groupId> < artifactId > GRPC - protobuf < / artifactId > < version > 1.45.0 < / version > < / dependency > <! -- https://mvnrepository.com/artifact/io.grpc/grpc-stub --> <dependency> <groupId>io.grpc</groupId> <artifactId>grpc-stub</artifactId> <version>1.45.0</version> </dependency> <dependency> <! -- necessary for Java 9+ --> <groupId>org.apache.tomcat</groupId> <artifactId>annotations-api</artifactId> The < version > 6.0.53 < / version > < scope > provided < / scope > < / dependency > <! -- This is needed to override a managed guava dependency--> <dependency> <groupId>com.google.guava</groupId> The < artifactId > guava < / artifactId > < version > 21.0 < / version > < / dependency > < / dependencies >Copy the code

We also need to add related plug-ins to our Maven files.

After configuring the dependencies, then define the server interface proto protocol in the.prot file.

syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.code_examples.grpc.v1";
service HelloWorldService {
rpc ExecuteOrder(HelloRequest) returns (HelloResponse) {};
}
message HelloRequest {
string greetings = 1;
}
message HelloResponse {
string info = 1;
}
Copy the code

Next, use MVN Clean Install to build the project. This step automatically generates STUBS and Abstract files. When using the IDE to reference the classes we create, be sure to add them to the classpath.

Then create a Service class and rewrite the executeOrder () method of the base class.

@Override public void executeOrder(com.code_examples.grpc.v1.HelloRequest request,io.grpc.stub.StreamObserver<com.code_examples.grpc.v1.HelloResponse> responseObserver) { HelloResponse response = HelloResponse.newBuilder().setInfo(request.getGreetings()).build(); responseObserver.onNext(response); responseObserver.onCompleted(); }Copy the code

In this service, we read information from the request and send it back to the client as a response.

Finally, we create a class to start the server.

public static void main(String[] args) throws IOException, InterruptedException {
    Server server = ServerBuilder.forPort(8085).addService(new HelloWorldServiceImpl()).build();
    server.start();
    server.awaitTermination();
}
Copy the code

In the main method, we call the service implemented above and start the server on port 8085.

Finally, we run the main method to finish starting the server.

Client-side implementation

Create a client class and send a message to the server.

ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost",8085).usePlaintext().build();
HelloWorldServiceBlockingStub orderServiceBlockingStub = HelloWorldServiceGrpc.newBlockingStub(managedChannel);
HelloRequest helloReq = HelloRequest.newBuilder().setGreetings("Hey Foo").build();
HelloResponse helloResponse = orderServiceBlockingStub.executeOrder(helloReq);
System.out.println("Received response: " + helloResponse.getInfo());
managedChannel.shutdown();
Copy the code

Run the client class and verify the check output. Below is the response from the server.