gRPC Javaコンバット:Mavenプラグインを介してprotoファイルに基づいてJavaコードを自動的に生成します

1問題:公式のgRPCドキュメントは十分に詳細ではありません

gRPC javaを調査しているときに問題が発生しました。公式ドキュメントによると、サンプルを一度に正常に実行する方法はありません。

代わりに、protoコンパイラ、maven、gRPC-javaの関係を理解するために、さまざまなドキュメントを調べるのに丸2日かかりました。

ここで、一度に実行することが保証できるエンドツーエンドのgRPC-javaサンプルプログラムを提供します。

2Mavenを介してJavaプロジェクトをビルドします

javaバージョン:1.8
gRPCバージョン:1.29.0pom.xml
コア構成部分

2.1Pomコアの依存関係

<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.2pom構成プロトプラグイン

os-maven-plugin:このプラグインは現在のシステム情報を検出できます
$ {os.detected.classifier}:この変数はオペレーティングシステムのバージョンを取得します(例: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プロトファイルを定義します

helloworld.protoファイルをsrc / main / protoディレクトリに配置します
コード編成構造

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

4Mavenプラグインを介してprotoに基づいてJavaコードを生成します

実行mvn compileコマンドコードが自動生成されます。
デフォルトで生成されるコードは、target / generate-sources / protobufディレクトリにあります。
grpc-javaディレクトリには、生成されたサービスに対応するクラスが含まれ、javaディレクトリには、生成されたメッセージに対応するjavaオブジェクトが含まれます。

Mavenによって生成されたコードが配置されているパス

5 gRPC-java、サーバー側のコード例

main関数を直接実行すると、サーバーが動作を開始します。

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、クライアント側のコード例

main関数が実行されるたびに、クライアントはサーバーに要求を送信するのと同じです。

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

7gRPC-javaサンプルコードの実行結果

ここに画像の説明を挿入

8リファレンス

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

おすすめ

転載: blog.csdn.net/hugo_lei/article/details/106098217