gRPC 同步调用超时设置:代码示例及异常处理
在 gRPC 中,同步调用超时时间可以通过客户端的 Channel 对象的 'withDeadline' 方法进行设置。示例代码如下:
ManagedChannel channel = ManagedChannelBuilder.forAddress('localhost', 8080)
.usePlaintext()
.build();
FooServiceGrpc.FooServiceBlockingStub stub = FooServiceGrpc.newBlockingStub(channel);
// 设置超时时间为 5 秒
long timeout = 5L;
stub = stub.withDeadlineAfter(timeout, TimeUnit.SECONDS);
// 发起 RPC 调用
FooResponse response = stub.foo(FooRequest.newBuilder().build());
在上述示例代码中,通过 'stub.withDeadlineAfter(timeout, TimeUnit.SECONDS)' 方法将超时时间设置为 5 秒。如果在 5 秒内没有接收到响应,调用会抛出 'StatusRuntimeException' 异常。如果不设置超时时间,则调用会一直等待响应,直到服务器返回结果或者出现错误。
原文地址: https://www.cveoy.top/t/topic/l4L9 著作权归作者所有。请勿转载和采集!