gRPC java combat: automatically generate java code based on the proto file through the maven plug-in

1 Problem: The official gRPC documentation is not detailed enough

I encountered a problem when investigating gRPC java. According to the official documentation, there is no way to run the example successfully in one go.

Instead, it took two full days to look through various documents to figure out the relationship between proto compiler, maven, and gRPC-java.

Now provide an end-to-end gRPC-java sample program that can be guaranteed to run at one time.

2 Build a java project through maven

java version: 1.8
gRPC version: 1.29.0
pom.xml core configuration part

2.1 Pom core dependencies

<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-netty-shaded</artifactId>
  <version>1.29.0</version>
</dependency>
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-protobuf</artifactId>
  <version>1.29.0</version>
</dependency>
<dependency>
  <groupId>io.grpc</groupId>
  <artifactId>grpc-stub</artifactId>
  <version>1.29.0</version>
</dependency>
<!-- necessary for Java 9+ -->
<!--java 低于 1.8 的版本不需要此依赖-->
<dependency> 
  <groupId>org.apache.tomcat</groupId>
  <artifactId>annotations-api</artifactId>
  <version>6.0.53</version>
  <scope>provided</scope>
</dependency>

2.2 pom configuration proto plugin

os-maven-plugin: This plugin can detect the current system information
${os.detected.classifier}: This variable gets the version of the operating system, for example, osx-x86_64

<build>
  <extensions>
    <extension>
      <groupId>kr.motd.maven</groupId>
      <artifactId>os-maven-plugin</artifactId>
      <version>1.6.2</version>
    </extension>
  </extensions>
  <plugins>
    <plugin>
      <groupId>org.xolstice.maven.plugins</groupId>
      <artifactId>protobuf-maven-plugin</artifactId>
      <version>0.6.1</version>
      <configuration>
        <protocArtifact>com.google.protobuf:protoc:3.11.0:exe:${
    
    os.detected.classifier}</protocArtifact>
        <pluginId>grpc-java</pluginId>
        <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.29.0:exe:${
    
    os.detected.classifier}</pluginArtifact>
      </configuration>
      <executions>
        <execution>
          <goals>
            <goal>compile</goal>
            <goal>compile-custom</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

3 Define the proto file

Put the helloworld.proto file in the src/main/proto directory
Code organization structure

syntax = "proto3";

option java_generic_services = true;
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";

// 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;
}

4 Generate java code based on proto through the maven plugin

Execution mvn compilecommand code is automatically generated.
The default generated code is in the target/generated-sources/protobuf directory.
The grpc-java directory contains the class corresponding to the generated Service, and the java directory contains the java object corresponding to the generated message.

The path where the code generated by maven is located

5 gRPC-java, server-side code example

Run the main function directly, and the server starts to work.

package io.grpc.examples.helloworld;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

/**
 * @ClassName HelloWorldServer
 * @Description
 * @Author hugo_lei
 * @Date 13/5/20 上午11:09
 */
public class HelloWorldServer {
    
    


    private Server server;

    private void start() throws IOException {
    
    
        /* The port on which the server should run */
        int port = 50051;
        server = ServerBuilder.forPort(port)
                .addService(new GreeterImpl())
                .build()
                .start();
        Runtime.getRuntime().addShutdownHook(new Thread() {
    
    
            @Override
            public void run() {
    
    
                // Use stderr here since the logger may have been reset by its JVM shutdown hook.
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                try {
    
    
                    HelloWorldServer.this.stop();
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace(System.err);
                }
                System.err.println("*** server shut down");
            }
        });
    }

    private void stop() throws InterruptedException {
    
    
        if (server != null) {
    
    
            server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
        }
    }

    /**
     * Await termination on the main thread since the grpc library uses daemon threads.
     */
    private void blockUntilShutdown() throws InterruptedException {
    
    
        if (server != null) {
    
    
            server.awaitTermination();
        }
    }

    /**
     * Main launches the server from the command line.
     */
    public static void main(String[] args) throws IOException, InterruptedException {
    
    
        final HelloWorldServer server = new HelloWorldServer();
        server.start();
        server.blockUntilShutdown();
    }

    static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
    
    

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

6 gRPC-java, client-side code example

Every time the main function is executed, the client is equivalent to sending a request to the server.

package io.grpc.examples.helloworld;

import java.util.concurrent.TimeUnit;

import io.grpc.Channel;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;

/**
 * @ClassName HelloWorldClient
 * @Description
 * @Author hugo_lei
 * @Date 13/5/20 上午11:13
 */
public class HelloWorldClient {
    
    

    private final GreeterGrpc.GreeterBlockingStub blockingStub;

    /** Construct client for accessing HelloWorld server using the existing channel. */
    public HelloWorldClient(Channel channel) {
    
    
        // 'channel' here is a Channel, not a ManagedChannel, so it is not this code's responsibility to
        // shut it down.

        // Passing Channels to code makes code easier to test and makes it easier to reuse Channels.
        blockingStub = GreeterGrpc.newBlockingStub(channel);
    }

    /** Say hello to server. */
    public void greet(String name) {
    
    
        HelloRequest request = HelloRequest.newBuilder().setName(name).build();
        HelloReply response;
        try {
    
    
            response = blockingStub.sayHello(request);
        } catch (StatusRuntimeException e) {
    
    
            return;
        }
        System.out.println("Greeting: " + response.getMessage());
    }

    /**
     * Greet server. If provided, the first element of {@code args} is the name to use in the
     * greeting. The second argument is the target server.
     */
    public static void main(String[] args) throws Exception {
    
    
        String user = "hahahahah";
        // Access a service running on the local machine on port 50051
        String target = "localhost:50051";
        // Allow passing in the user and target strings as command line arguments
        if (args.length > 0) {
    
    
            if ("--help".equals(args[0])) {
    
    
                System.err.println("Usage: [name [target]]");
                System.err.println("");
                System.err.println("  name    The name you wish to be greeted by. Defaults to " + user);
                System.err.println("  target  The server to connect to. Defaults to " + target);
                System.exit(1);
            }
            user = args[0];
        }
        if (args.length > 1) {
    
    
            target = args[1];
        }

        // Create a communication channel to the server, known as a Channel. Channels are thread-safe
        // and reusable. It is common to create channels at the beginning of your application and reuse
        // them until the application shuts down.
        ManagedChannel channel = ManagedChannelBuilder.forTarget(target)
                // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
                // needing certificates.
                .usePlaintext()
                .build();
        try {
    
    
            HelloWorldClient client = new HelloWorldClient(channel);
            client.greet(user);
        } finally {
    
    
            // ManagedChannels use resources like threads and TCP connections. To prevent leaking these
            // resources the channel should be shut down when it will no longer be used. If it may be used
            // again leave it running.
            channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
        }
    }
}

7 gRPC-java sample code running results

Insert picture description here

8 Reference

  1. grpc-java
  2. os-maven-plugin
  3. protobuf-maven-plugin

Guess you like

Origin blog.csdn.net/hugo_lei/article/details/106098217