Grpc Server keeps processing the data even when cl

2020-07-23 06:55发布

问题:

I have a server which streams the data for a given request below is the method which does that function

@Override
public void getChangeFeed(ChangeFeedRequest request, StreamObserver<ChangeFeedResponse> responseObserver) {
    long queryDate = request.getFromDate();
    long offset = request.getPageNo();
    ChangeFeedResponse changeFeedResponse =  processData(responseObserver, queryDate, offset);

    while(true){
        if(changeFeedResponse!=null && !changeFeedResponse.getFinalize()){
            responseObserver.onNext(changeFeedResponse);
           changeFeedResponse = processData(responseObserver, changeFeedResponse.getToDate(), changeFeedResponse.getPageNo());
        }else{
            break;
        }
    }
    responseObserver.onNext(changeFeedResponse);
    responseObserver.onCompleted();
}

When the client get disconnected the server still keeps on processing, this might be issue when multiple clients are fetching the data. Need to know how to tell server to stop processing

回答1:

There's two fairly-equivalent ways. One is to use the Context, which is cancelled when the RPC is completed/cancelled:

while(!Context.current().isCancelled()){ // THIS LINE CHANGED
    if(changeFeedResponse!=null && !changeFeedResponse.getFinalize()){
        responseObserver.onNext(changeFeedResponse);
       changeFeedResponse = processData(responseObserver, changeFeedResponse.getToDate(), changeFeedResponse.getPageNo());
    }else{
        break;
    }
}

The other would be to use the ServerCallStreamObserver:

// THE NEXT TWO LINES CHANGED
ServerCallStreamObserver scso = (ServerCallStreamObserver) responseObserver;
while(!scso.isCancelled()){
    if(changeFeedResponse!=null && !changeFeedResponse.getFinalize()){
        responseObserver.onNext(changeFeedResponse);
       changeFeedResponse = processData(responseObserver, changeFeedResponse.getToDate(), changeFeedResponse.getPageNo());
    }else{
        break;
    }
}

Both approaches can also provide notification when a cancellation occurs, but polling is easiest in your case.