The advantages of Grpc are not mentioned here. First, it is based on Http2.0 protocol and can maintain long connection between client and server. It is based on binary stream, i.e. byte stream, not text stream.

He also provides cross-platform development, but he also has the cost of defining his interface specification, following his set of specifications, which means that even if you are a Java language, you can’t just define an interface, I can implement RPC for you, but he can help you generate an interface that meets his specification.

The POM configuration is at the end of the article

Quick start

1. Rely on:

<dependency>
    <groupId>io.grpc</groupId>
    <artifactId>grpc-all</artifactId>
    <version>1.12.0</version>
</dependency>
Copy the code

Plug-ins and all dependencies are at the end of the article. Global paste

2. Compile a Protobuf file

Idea mind downloading a protobuf plugin that can have code hints. Just go straight to pluging here.

I’m using the Proto3 version.

Can consult this article www.cnblogs.com/tohxyblog/p…

Note that this file is defined in your SRC /proto/ xx.proto file directory must be written.

syntax = "proto3"; // Protocol version

// Option configuration
option java_package = "com.example.grpc.api";
option java_outer_classname = "RPCDateServiceApi";
option java_multiple_files = true;

// Define the package name
package com.example.grpc.api;

// Service interface. Define the request parameters and corresponding results
service RPCDateService {
    rpc getDate (RPCDateRequest) returns (RPCDateResponse) {}}// Define the request body
message RPCDateRequest {
    string userName = 1;
}

// Define the corresponding content
message RPCDateResponse {
    string serverDate = 1;
}
Copy the code

Using the Maven plugin, compile.

The first command is executed. Just look in the Target directory. The second command is also to find. Then copy the generated Java files to your directory. Mapper plugin similar to Mybatis.

3. Write interface implementation classes.

package com.example.grpc.service;

/ / RPCDateServiceGrpc RPCDateServiceImplBase is the interface.
// RPCDateServiceImpl we need to inherit his implementation method callback
public class RPCDateServiceImpl extends RPCDateServiceGrpc.RPCDateServiceImplBase {
    @Override
    public void getDate(RPCDateRequest request, StreamObserver<RPCDateResponse> responseObserver) {
        // Request the result, as defined by us
        RPCDateResponse rpcDateResponse = null;
        String userName = request.getUserName();
        String response = String.format("Hello: % S, today is % S.", userName, LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        try {
            // Define the response, which is a Builder constructor.
            rpcDateResponse = RPCDateResponse
                    .newBuilder()
                    .setServerDate(response)
                    .build();
        } catch (Exception e) {
            responseObserver.onError(e);
        } finally {
            // This is an observer.responseObserver.onNext(rpcDateResponse); } responseObserver.onCompleted(); }}Copy the code

Defining the server

public class GRPCServer {
    private static final int port = 9999;

    public static void main(String[] args) throws Exception {
        // Set the service interface.
        Server server = ServerBuilder.
                forPort(port)
                .addService(new RPCDateServiceImpl())
                .build().start();
        System.out.println(String.format("GRpc server started successfully, port number: %d.", port)); server.awaitTermination(); }}Copy the code

Defining the client

public class GRPCClient {
    private static final String host = "localhost";
    private static final int serverPort = 9999;

    public static void main(String[] args) throws Exception {
        // 1. Get a channel for communication
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress(host, serverPort).usePlaintext().build();
        try {
            // 2
            RPCDateServiceGrpc.RPCDateServiceBlockingStub rpcDateService = RPCDateServiceGrpc.newBlockingStub(managedChannel);
            RPCDateRequest rpcDateRequest = RPCDateRequest
                    .newBuilder()
                    .setUserName("anthony")
                    .build();
            / / 3. Request
            RPCDateResponse rpcDateResponse = rpcDateService.getDate(rpcDateRequest);
            // 4. Output the result
            System.out.println(rpcDateResponse.getServerDate());
        } finally {
            // 5. Close the channel to release resources.managedChannel.shutdown(); }}}Copy the code

So that’s the whole process. Start the server side, start the client side print the information:

Server logs:

2020-02-29 11:04:50.991 4689   [LG-3-1] DEBUG .grpc.netty.NettyServerHandler  - [id: 0xed01e3fb, L:/127.00.1:9999 - R:/127.00.1:3994] INBOUND SETTINGS: ack=true
2020-02-29 11:04:51.075 4773   [LG-3-1] DEBUG .grpc.netty.NettyServerHandler  - [id: 0xed01e3fb, L:/127.00.1:9999 - R:/127.00.1:3994] INBOUND HEADERS: streamId=3 headers=GrpcHttp2RequestHeaders[:path: /com.example.grpc.api.RPCDateService/getDate, :authority: localhost:9999, :method: POST, :scheme: http, te: trailers, content-type: application/grpc, user-agent: grpc-java-netty/1.12.0, grpc-accept-encoding: gzip, grpc-trace-bin: ] streamDependency=0 weight=16 exclusive=false padding=0 endStream=false
2020-02-29 11:04:51.125 4823   [LG-3-1] DEBUG .grpc.netty.NettyServerHandler  - [id: 0xed01e3fb, L:/127.00.1:9999 - R:/127.00.1:3994] INBOUND DATA: streamId=3 padding=0 endStream=true length=14 bytes=00000000090a07616e74686f6e79
2020-02-29 11:04:51.172 4870   [LG-3-1] DEBUG .grpc.netty.NettyServerHandler  - [id: 0xed01e3fb, L:/127.00.1:9999 - R:/127.00.1:3994] OUTBOUND HEADERS: streamId=3 headers=GrpcHttp2OutboundHeaders[:status: 200, content-type: application/grpc, grpc-encoding: identity, grpc-accept-encoding: gzip] streamDependency=0 weight=16 exclusive=false padding=0 endStream=false
2020-02-29 11:04:51.189 4887   [LG-3-1] DEBUG .grpc.netty.NettyServerHandler  - [id: 0xed01e3fb, L:/127.00.1:9999 - R:/127.00.1:3994] OUTBOUND DATA: streamId=3 padding=0 endStream=false length=44 bytes=00000000270a25e4bda0e5a5bd3a20616e74686f6e792c20e4bb8ae5a4a9e698af323032302d30322d32392e
2020-02-29 11:04:51.190 4888   [LG-3-1] DEBUG .grpc.netty.NettyServerHandler  - [id: 0xed01e3fb, L:/127.00.1:9999 - R:/127.00.1:3994] OUTBOUND HEADERS: streamId=3 headers=GrpcHttp2OutboundHeaders[grpc-status: 0] streamDependency=0 weight=16 exclusive=false padding=0 endStream=true
2020-02-29 11:04:51.204 4902   [LG-3-1] DEBUG .grpc.netty.NettyServerHandler  - [id: 0xed01e3fb, L:/127.00.1:9999 - R:/127.00.1:3994] INBOUND GO_AWAY: lastStreamId=0 errorCode=0 length=0 bytes=
Copy the code

Client logging:

2020-02-29 11:00:43.480 1814   [LG-1-2] DEBUG .grpc.netty.NettyClientHandler  - [id: 0xcdbd6064, L:/127.00.1:3817 - R:localhost/127.00.1:9999] INBOUND HEADERS: streamId=3 headers=GrpcHttp2ResponseHeaders[grpc-status: 0] streamDependency=0 weight=16 exclusive=false padding=0 endStream=trueHello, Anthony20-02-29.
2020-02-29 11:00:43.487 1821   [LG-1-2] DEBUG .grpc.netty.NettyClientHandler  - [id: 0xcdbd6064, L:/127.00.1:3817 - R:localhost/127.00.1:9999] OUTBOUND GO_AWAY: lastStreamId=0 errorCode=0 length=0 bytes=
Copy the code

This is the complete process of a Grpc.

Let’s analyze it.

Definition is a CS model, GRPC he saw the future must be HTTP2 world (this is an inevitable trend), so he did not develop their own protocol, here refers to the application layer protocol. Similar to our RestTemplate is HTTP based.

So he was thinking about JSON, which is a slower serialization. A Protobuf developed by ourselves is used.

GRPC is really just a way to serialize, depending on the Protobuf, can solve a series of problems, such as interface information definition, and so on,

For example, if I write an echo() interface in Java, how do I call golang? .and that’s the hard part.

We can rely on a unified Protobuf file to generate the corresponding Golang and Java interfaces, so essentially that’s what he did.

Let’s see what Dubbo did. He built his own application layer protocol, Dubbo, based on TCP’s reliability. It also references a bunch of serialization methods, so the whole GRPC works.

Interested students can do a packet capture, capture client request, analysis of a GRPC request format.

Pom file

<?xml version="1.0" encoding="UTF-8"? >
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.examole</groupId>
    <artifactId>grpc-study-demo-01</artifactId>
    <version>1.0 the SNAPSHOT</version>


    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>

        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-all</artifactId>
            <version>1.12.0</version>
        </dependency>


    </dependencies>
    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.4.1. The Final</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.5.0</version>
                <configuration>
                    <pluginId>grpc-java</pluginId>
                    <protocArtifact>Com. Google. Protobuf: protoc: 3.0.2: exe: ${OS. Detected. Classifier}</protocArtifact>
                    <pluginArtifact>IO. GRPC: protoc - gen - GRPC - Java: 1.2.0: exe: ${OS. Detected. Classifier}</pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
Copy the code