クイックスタート

このガイドでは、簡単な動作例を使用して、JavaでのgRPCの始め方を紹介します。

クイックスタート

このガイドでは、簡単な動作例を使用して、JavaでのgRPCの始め方を紹介します。

前提条件

  • JDK バージョン7以上

サンプルコードの取得

サンプルコードは、grpc-javaリポジトリの一部です。

  1. リポジトリをZIPファイルとしてダウンロードして解凍するか、リポジトリをクローンします。

    $ git clone -b v1.63.0 --depth 1 https://github.com/grpc/grpc-java
    
  2. examplesディレクトリに移動します。

    $ cd grpc-java/examples
    

サンプルの実行

examplesディレクトリから

  1. クライアントとサーバーをコンパイルします。

    $ ./gradlew installDist
    
  2. サーバーを実行します。

    $ ./build/install/examples/bin/hello-world-server
    INFO: Server started, listening on 50051
    
  3. 別のターミナルから、クライアントを実行します。

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

おめでとうございます!gRPCを使用してクライアント/サーバーアプリケーションを実行しました。

gRPCサービスの更新

このセクションでは、追加のサーバーメソッドを追加してアプリケーションを更新します。gRPCサービスは、Protocol Buffersを使用して定義されます。.protoファイルでサービスを定義する方法の詳細については、基本チュートリアルを参照してください。今のところ、知っておく必要があるのは、サーバーとクライアントスタブの両方に、クライアントからのHelloRequestパラメーターを受け取り、サーバーからHelloReplyを返すSayHello()RPCメソッドがあること、およびメソッドが次のように定義されていることです。

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

src/main/proto/helloworld.protoを開き、SayHello()と同じリクエストとレスポンスのタイプを持つ新しいSayHelloAgain()メソッドを追加します。

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

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

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

ファイルを保存することを忘れないでください!

アプリの更新

サンプルをビルドすると、ビルドプロセスは、生成されたgRPCクライアントとサーバーのクラスを含むGreeterGrpc.javaを再生成します。これにより、リクエストとレスポンスのタイプを設定、シリアライズ、および取得するためのクラスも再生成されます。

ただし、サンプルアプリの手書き部分で新しいメソッドを実装して呼び出す必要があります。

サーバーの更新

同じディレクトリで、src/main/java/io/grpc/examples/helloworld/HelloWorldServer.javaを開きます。次のように新しいメソッドを実装します。

// Implementation of the gRPC service on the server-side.
private class GreeterImpl extends GreeterGrpc.GreeterImplBase {

  @Override
  public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    // Generate a greeting message for the original method
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();

    // Send the reply back to the client.
    responseObserver.onNext(reply);

    // Indicate that no further messages will be sent to the client.
    responseObserver.onCompleted();
  }

  @Override
  public void sayHelloAgain(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
    // Generate another greeting message for the new method.
    HelloReply reply = HelloReply.newBuilder().setMessage("Hello again " + req.getName()).build();

    // Send the reply back to the client.
    responseObserver.onNext(reply);

    // Indicate that no further messages will be sent to the client.
    responseObserver.onCompleted();
  }
}

クライアントの更新

同じディレクトリで、src/main/java/io/grpc/examples/helloworld/HelloWorldClient.javaを開きます。次のように新しいメソッドを呼び出します。

// Client-side logic for interacting with the gRPC service.
public void greet(String name) {
  // Log a message indicating the intention to greet a user.
  logger.info("Will try to greet " + name + " ...");

  // Creating a request with the user's name.
  HelloRequest request = HelloRequest.newBuilder().setName(name).build();
  HelloReply response;
  try {
    // Call the original method on the server.
    response = blockingStub.sayHello(request);
  } catch (StatusRuntimeException e) {
    // Log a warning if the RPC fails.
    logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
    return;
  }

  // Log the response from the original method.
  logger.info("Greeting: " + response.getMessage());

  try {
    // Call the new method on the server.
    response = blockingStub.sayHelloAgain(request);
  } catch (StatusRuntimeException e) {
    // Log a warning if the RPC fails.
    logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
    return;
  }

  // Log the response from the new method.
  logger.info("Greeting: " + response.getMessage());
}

更新されたアプリの実行

以前と同様にクライアントとサーバーを実行します。examplesディレクトリから次のコマンドを実行します。

  1. クライアントとサーバーをコンパイルします。

    $ ./gradlew installDist
    
  2. サーバーを実行します。

    $ ./build/install/examples/bin/hello-world-server
    INFO: Server started, listening on 50051
    
  3. 別のターミナルから、クライアントを実行します。

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

次のステップ