use of com.hry.spring.grpc.mystream.SimpleSummary in project spring_boot by hryou0922.
the class HelloStreamClient method client2ServerRpc.
/**
* 异步客户端流
*/
public void client2ServerRpc(int count) throws InterruptedException {
logger.info("request client2ServerRpc {}", count);
final CountDownLatch finishLatch = new CountDownLatch(1);
StreamObserver<SimpleSummary> responseObserver = new StreamObserver<SimpleSummary>() {
@Override
public void onNext(SimpleSummary value) {
// 返回SimpleSummary
logger.info("client2ServerRpc onNext : {}", value);
}
@Override
public void onError(Throwable t) {
logger.error("client2ServerRpc error : {}", t);
finishLatch.countDown();
}
@Override
public void onCompleted() {
logger.error("client2ServerRpc finish");
finishLatch.countDown();
}
};
StreamObserver<Simple> requestObserver = asyncStub.client2ServerRpc(responseObserver);
try {
for (int i = 0; i < count; i++) {
logger.info("simple2 : {}", i);
Simple simple = Simple.newBuilder().setName("client2ServerRpc" + i).setNum(i).build();
requestObserver.onNext(simple);
Thread.sleep(random.nextInt(200) + 50);
}
} catch (RuntimeException e) {
// Cancel RPC
requestObserver.onError(e);
throw e;
}
// 结束请求
requestObserver.onCompleted();
// Receiving happens asynchronously
if (!finishLatch.await(1, TimeUnit.MINUTES)) {
logger.error("client2ServerRpc can not finish within 1 minutes");
}
}
Aggregations