クイックスタート

このガイドでは、シンプルな動作する例を使ってJavaでのgRPCの開始方法を説明します。

クイックスタート

このガイドでは、シンプルな動作する例を使ってJavaでのgRPCの開始方法を説明します。

前提条件

  • JDK バージョン7以降

サンプルコードを取得する

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

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

    git clone -b v1.73.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;
}

ファイルを保存してください!

アプリケーションを更新する

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

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

サーバーを更新する

同じディレクトリで、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
    

次は何をするか