【发布时间】:2020-08-26 16:51:15
【问题描述】:
我正在尝试开始使用 grpc for Android。
我找到了如何为单个请求设置超时(截止日期)。
有没有办法为所有请求设置超时?我真的不想在每个请求之前都设置截止日期
【问题讨论】:
我正在尝试开始使用 grpc for Android。
我找到了如何为单个请求设置超时(截止日期)。
有没有办法为所有请求设置超时?我真的不想在每个请求之前都设置截止日期
【问题讨论】:
您可以使用服务配置为每个方法提供默认值,也可以使用拦截器在通道级别设置截止日期。
Service config 可以通过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());
【讨论】: