Java版gRPCのサーバーのメモ。
protoファイルのビルドしてgRPCクライアントを作成するために、build.gradleに以下のように設定する。
plugins {
id 'java'
id 'application'
id 'com.google.protobuf' version '0.9.5'
}
group = 'com.example.grpc'
repositories {
mavenCentral()
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(25)
}
}
def grpcVersion = '1.81.0'
def protobufVersion = '3.25.8'
def protocVersion = protobufVersion
dependencies {
implementation "com.google.protobuf:protobuf-java:${protobufVersion}"
implementation "com.google.protobuf:protobuf-java-util:${protobufVersion}"
implementation "io.grpc:grpc-services:${grpcVersion}"
implementation "io.grpc:grpc-protobuf:${grpcVersion}"
implementation "io.grpc:grpc-stub:${grpcVersion}"
runtimeOnly "io.grpc:grpc-netty-shaded:${grpcVersion}"
}
protobuf {
protoc { artifact = "com.google.protobuf:protoc:${protocVersion}" }
plugins {
grpc { artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}" }
}
generateProtoTasks {
all()*.plugins { grpc {} }
}
}
application {
applicationName = 'grpc-example-server'
mainClass = 'com.example.grpc.server.GrpcExampleServer'
}
C++版gRPCサーバーのprotoファイルと同様のものを使用する。
syntax = "proto3";
package example.grpc;
option java_multiple_files = true;
option java_package = "com.example.grpc.proto";
message Int64PairRequest {
int64 first_value = 1;
int64 second_value = 2;
}
message Int64PairResponse {
int64 first_value = 1;
int64 second_value = 2;
}
service ExampleService {
rpc SendInt64Pair(Int64PairRequest) returns (Int64PairResponse);
}
protoファイルのservice毎に、RPCメソッド(プロシージャー)の実装を行う。
package com.example.grpc.server.service; import com.example.grpc.proto.ExampleServiceGrpc.ExampleServiceImplBase; import com.example.grpc.proto.Int64PairRequest; import com.example.grpc.proto.Int64PairResponse; import io.grpc.stub.StreamObserver;
public class ExampleServiceImpl extends ExampleServiceImplBase {
@Override
public void sendInt64Pair(Int64PairRequest request, StreamObserver<Int64PairResponse> responseObserver) {
long firstValue = request.getFirstValue();
long secondValue = request.getSecondValue();
System.out.printf("server: %d, %d%n", firstValue, secondValue);
var response = Int64PairResponse.newBuilder() //
.setFirstValue(firstValue) //
.setSecondValue(secondValue) //
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
mainメソッドを実装する。
サービスを実行してリクエストを待ち受けるクラスを実行する。
package com.example.grpc.server; import java.io.IOException; import com.example.grpc.server.service.ExampleServiceImpl; import io.grpc.ServerBuilder;
public class GrpcExampleServer {
public static void main(String[] args) throws IOException, InterruptedException {
int port = 50051;
var server = ServerBuilder.forPort(port) //
.addService(new ExampleServiceImpl()) //
.build().start();
System.out.printf("gRPC server started on port %d%n", server.getPort());
server.awaitTermination(); // クライアントからの呼び出しを待つ
}
}
pluginsに「id 'application'」が指定してあるので、gradleのrunタスクで実行できる。
cd プロジェクト ./gradlew run