Java版gRPCのクライアントのメモ。
|
C++版gRPCサーバーのprotoファイルと同じものを使用する。
syntax = "proto3";
package example.grpc;
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);
}
package com.example.grpc;
import example.grpc.ExampleServiceGrpc; import example.grpc.example.Int64PairRequest; import example.grpc.example.Int64PairResponse;
import io.grpc.Channel; import io.grpc.Grpc; import io.grpc.InsecureChannelCredentials; import io.grpc.ManagedChannel; import io.grpc.StatusRuntimeException;
public class Int64PairClient {
private final ExampleServiceGrpc.ExampleServiceBlockingStub blockingStub;
public Int64PairClient(Channel channel) {
this.blockingStub = ExampleServiceGrpc.newBlockingStub(channel);
}
protoファイルをJava向けにビルドすると、XxxStub・XxxBlockingStub・XxxFutureStubという具合に、複数のStubクラスが生成される。
基本はXxxStubだが、レスポンスの取得方法がちょっと面倒なので、BlockingStubにメソッドが生成されているなら、それを使うのが楽。
(protoファイルのプロシージャーの引数がstreamだと、BlockingStubにはメソッドが生成されない)
public Int64PairResponse sendInt64Pair(Int64PairRequest request) {
try {
return blockingStub.sendInt64Pair(request);
} catch (StatusRuntimeException e) {
e.printStackTrace();
return null;
}
}
protoファイルではプロシージャー名はCamelCaseで書かれているが、Java向けに生成されたメソッド名はcamelCase(先頭が小文字)になる。
public static void main(String[] args) throws Exception {
int port = 50051;
String target = "localhost:" + port;
System.out.printf("target=%s%n", target);
ManagedChannel channel = Grpc.newChannelBuilder(target, InsecureChannelCredentials.create()).build();
try (AutoCloseable c = () -> {
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}) {
var client = new Int64PairClient(channel);
var request = Int64PairRequest.newBuilder() //
.setFirstValue(i) //
.setSecondValue(456) //
.build();
var response = client.sendInt64Pair(request);
System.out.println(response);
}
}
}
shadowJarを生成しておけば、jarファイルにクラス名を指定して実行できる。
→build.gradleの記述例
cd プロジェクト ./gradlew shadowJar java -cp build/libs/grpc-example-all.jar com.example.grpc.Int64PairClient