简体   繁体   English

使用多个 ResponseObserver.onNext 会卡住服务 - gRPC Java

[英]Using multiple ResponseObserver.onNext will stuck the service - gRPC Java

I want to send data in chunks of 50 with gRPC, however when running responseObserver.onNext multiple times, it just get stuck and wont send the data.我想用 gRPC 以 50 个块发送数据,但是当多次运行responseObserver.onNext时,它只是卡住并且不会发送数据。 But when I stop the stream, I get the data.但是当我停止 stream 时,我得到了数据。

This is my code:这是我的代码:

// List<List<MyClass>> listOfMyClass
for (List<MyClass> myClasses : listOfMyClass) {
  responseObserver.onNext(buildReply(myClasses));
}
responseObserver.onCompleted();

This will make it stuck.这会让它卡住。 But, if I only run responseObserver.onNext(buildReply(myClasses));但是,如果我只运行responseObserver.onNext(buildReply(myClasses)); once, I will get the data instantly.一次,我会立即得到数据。

My proto:我的原型:

message Request {
    string number = 1;
}

message Reply {
    repeated CustomMessage results = 1;
}

service Service {
    rpc MyRequest (Request) returns (stream Reply) {}
}

I've been using a GUI called https://github.com/uw-labs/bloomrpc , which should display the stream easily.我一直在使用一个名为https://github.com/uw-labs/bloomrpc的 GUI,它应该可以轻松显示 stream。

The StreamObserver interface is non-blocking and doesn't provide back pressure for outbound data. StreamObserver接口是非阻塞的,不会为出站数据提供背压。 In order to give the client the back pressure, you need to cast the StreamObserver that the client uses to send the data to ServerCallStreamObserver, and observe the "ready" bit.为了给客户端提供背压,需要将客户端用来向ServerCallStreamObserver发送数据的StreamObserver进行强制转换,并观察“就绪”位。 Something like this:像这样的东西:

ClientCallStreamObserver<MyClass> clientCallStreamResponseObserver =
      (ClientCallStreamObserver<File>) responseObserver;
clientCallStreamObserver.setOnReadyHandler(new Runnable() {
    public void run() {
      sendUntilNotReady(clientCallStreamResponseObserver);
    }
});
sendUntilNotReady(clientCallStreamResponseObserver);

...

private void sendUntilNotReady(ClientCallStreamObserver<MyClass> clientCallStreamResponseObserver) {
  while (clientCallStreamResponseObserver.isReady()) {
    clientCallStreamResponseObserver.onNext(... /* build reply for next item in listOfMyClass */);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM