在截止日期之前调用grpc blockstub时如何管理应用程序崩溃

我正在尝试开发使用grpc阻止存根连接到后端服务器的应用程序。

我到了发出请求的地步,由于超过了截止日期,我的应用程序崩溃了。预期的行为是,当服务器无响应时(应用程序崩溃和关闭是不可接受的),try catch会处理。

以下是我的存根生成和错误:

    public LoginDataSource() {
    }

    public Result<LoggedInUser> login(String username, String password) {
        LoginServiceGrpc.LoginServiceBlockingStub blockingStub = LoginServiceGrpc.newBlockingStub(commChannel);
        GrpcServerComm.LoginData loginData = GrpcServerComm.LoginData.newBuilder().setUsername(username).setPassword(password).build();
        GrpcServerComm.LoginRequest serverResponse = blockingStub.withDeadlineAfter(2000, TimeUnit.MILLISECONDS).getLogin(loginData);
        long serverResponseVal = 0;
        try
        {
            LoggedInUser activeUser = new LoggedInUser(username,username);
            serverResponseVal = serverResponse.getResponseVal();
            return new Result.Success<>(activeUser);
        }
        catch (Exception e)
        {
            return new Result.Error(new IOException("Error logging in", e));
        }

    }

调试:

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.equinox.openeyes, PID: 2401
    io.grpc.StatusRuntimeException: DEADLINE_EXCEEDED: deadline exceeded after 1766623100ns. [buffered_nanos=1774305900, waiting_for_connection]
        at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.java:240)
        at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:221)
        at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:140)
        at com.equinox.openeyes.LoginServiceGrpc$LoginServiceBlockingStub.getLogin(LoginServiceGrpc.java:155)
评论
  • awzse
    awzse 回复

    尝试这个

    public MutableLiveDataResult<LoggedInUser> login(String username, String password) {
    
            MutableLiveDataResult<LoggedInUser> observeable = new MutableLiveDataResult<LoggedInUser>();
            LoginServiceGrpc.LoginServiceBlockingStub service = LoginServiceGrpc.newStub(commChannel);
            GrpcServerComm.LoginData loginData = GrpcServerComm.LoginData.newBuilder().setUsername(username).setPassword(password).build();
            service.getLogin(loginData, new StreamObserver<LoggedInUser> {
    
                public void onNext(LoggedInUser response) {
                    observeable.postValue(response);
                }
    
                public void onError(Throwable t) {
                    observeable.postValue(null);
                }
    
                public void onCompleted(Throwable t) {
                    // if you wanna close your channel
                    // commChannel.shutdown();
                } 
            })
            return observable;
        }
    

    And observe the changes in the MutableLiveData and get your result there.