首页 > 解决方案 > Java netty/okhttp gRPC 客户端在尝试连接时抛出间歇性 UNAVAILABLE:io 异常

问题描述

我正在尝试使用 java GRPC 客户端(netty 和 okhttp)连接到服务器。但是他们俩都间歇性地抛出 UNAVAILABLE: io 异常。

发生是随机的,我们不知道是什么导致了这种行为。我们发现请求没有到达 go 服务器。

用于连接的阻塞存根类似于:

public SomeServiceGrpc.SomeServiceBlockingStub getBlockingStub() {

        ManagedChannel channel = OkHttpChannelBuilder
                .forAddress(configuration.getHost(), configuration.getPort())
                .useTransportSecurity()
                .keepAliveTime(1, TimeUnit.MINUTES)
                .keepAliveTimeout(5, TimeUnit.SECONDS)
                .intercept(deadlineInterceptor)
                .build();
        return SomeServiceGrpc.newBlockingStub(channel);
    }

这些是用于 okhttp 和 protobuf 的库:

    compile 'io.grpc:grpc-okhttp:1.21.0'
    compile 'io.grpc:grpc-protobuf:1.20.0'
    compile 'io.grpc:grpc-stub:1.20.0'

这些是用于 netty 和 protobuf 的库:

    compile group: 'io.grpc', name: 'grpc-netty', version: '1.22.1'
    compile group: 'io.netty', name: 'netty-handler', version: '4.1.35.Final'
    compile group: 'io.netty', name: 'netty-tcnative-boringssl-static', version: '2.0.25.Final'
    compile 'io.grpc:grpc-protobuf:1.20.0'
    compile 'io.grpc:grpc-stub:1.20.0'

任何帮助或领导表示赞赏。

标签: nettyokhttpgrpc-java

解决方案


通过在客户端和服务器端将 keepAliveWithoutCalls 添加为 true 来解决它。

public SomeServiceGrpc.SomeServiceBlockingStub getBlockingStub() {

        ManagedChannel channel = OkHttpChannelBuilder
                .forAddress(configuration.getHost(), configuration.getPort())
                .useTransportSecurity()
                .keepAliveTime(1, TimeUnit.MINUTES)
                .keepAliveTimeout(5, TimeUnit.SECONDS)
                .keepAliveWithoutCalls(true)
                .intercept(deadlineInterceptor)
                .build();
        return SomeServiceGrpc.newBlockingStub(channel);
    }

推荐阅读