Grpc Server keeps processing the data even when client get disconnected

淺唱寂寞╮ 提交于 2019-12-06 07:24:00

问题


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.



来源:https://stackoverflow.com/questions/51080221/grpc-server-keeps-processing-the-data-even-when-client-get-disconnected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!