DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 gRPC 报错 UNAVAILABLE io exception channel shutdown 修复

排查 gRPC 客户端调用服务抛出 StatusRuntimeException: UNAVAILABLE: io exception / Subchannel shutdown 错误,配置 keepalive 与 DNS 服务发现。

问题现象

使用 gRPC Stub 发起远程过程调用时抛出不可用异常:

io.grpc.StatusRuntimeException: UNAVAILABLE: 
io exception
Channel shutdown invoked / Subchannel closed transport

触发根因

  1. 网络防火墙或代理长连接超时掐断:中间路由器或负载均衡器(如 AWS NLB/ALB、Nginx)在空闲超时后默默断开了底层 HTTP/2 TCP 连接,而客户端 Channel 毫不知情,在发起 RPC 时复用了已断开的 Subchannel;
  2. 服务端已重启或崩溃;
  3. gRPC 客户端通道未配置保活(KeepAlive)探活心跳。

解决步骤

1. 为 ManagedChannel 开启客户端 KeepAlive 心跳探活

在创建客户端 Channel 时配置主动保活参数:

ManagedChannel channel = ManagedChannelBuilder.forTarget("myservice:50051")
    .usePlaintext()
    .keepAliveTime(30, TimeUnit.SECONDS)       // 每 30 秒发送一次 HTTP/2 PING
    .keepAliveTimeout(5, TimeUnit.SECONDS)     // PING 响应超时时间为 5 秒
    .keepAliveWithoutCalls(true)               // 即使当前没有 RPC 也在后台探活
    .build();

2. 在服务端同步放宽 KeepAlive 允许频次

避免服务端判定客户端频繁发送 PING 为滥用而触发 GOAWAY:

Server server = ServerBuilder.forPort(50051)
    .addService(new MyServiceImpl())
    .permitKeepAliveTime(20, TimeUnit.SECONDS)
    .permitKeepAliveWithoutCalls(true)
    .build()
    .start();

验证确认

在连接保持空闲超过 10 分钟后再次触发 RPC 调用:

MyResponse resp = stub.getData(MyRequest.newBuilder().build());
assertNotNull(resp);

调用顺畅返回,无连接中断异常。