我正在尝试开始使用 grpc for Android。
我找到了如何为单个请求设置超时(截止日期)。
有没有办法为所有请求设置超时?我真的不想在每个请求之前设置截止日期
您可以使用服务配置为每个方法提供默认值,也可以使用拦截器在通道级别设置截止日期。
服务配置可以通过managedChannelBuilder.defaultServiceConfig(Map)
. 您可以根据不同的方法选择设置不同的超时时间。理想情况下,此配置将由服务所有者管理。
Map<String, Object> wildcardConfig = new HashMap<>();
wildcardConfig.put("name", Collections.singletonList(
// This would specify a service+method if you wanted
// different methods to have different settings
Collections.emptyMap()));
wildcardConfig.put("timeout", "10s");
channelBuilder.defaultServiceConfig(
Collections.singletonMap("methodConfig", Collections.singletonList(
wildcardConfig)));
拦截器可以通过stub.withInterceptors()
. 创建一个将添加默认超时的拦截器如下所示:
class TimeoutInterceptor implements ClientInterceptor {
@Override public <ReqT,RespT> ClientCall<ReqT,RespT> interceptCall(
MethodDescriptor<ReqT,RespT> method, CallOptions callOptions, Channel next) {
callOptions = callOptions.withDeadlineAfter(10, TimeUnit.SECONDS);
return next.newCall(method, callOptions);
}
}
stub = stub.withInterceptors(new TimeoutInterceptor());