简体   繁体   English

如何为 Java / Kotlin / Android 中的所有请求设置 gRPC 客户端超时

[英]How to set gRPC Client Timeout for all requests in Java / Kotlin / Android

I am trying to start using grpc for Android.我正在尝试开始为 Android 使用 grpc。

I found how to set timeout (deadline) for single request.我找到了如何为单个请求设置超时(截止日期)。

Is there any way to set timeout for all requests?有没有办法为所有请求设置超时? I really do not want to set deadline before every request我真的不想在每个请求之前设置截止日期

You can use service config to provide defaults on a per-method basis, or you can use an interceptor to set deadlines at a channel-level.您可以使用服务配置为每个方法提供默认值,或者您可以使用拦截器在通道级别设置截止日期。

Service config can be specified via managedChannelBuilder.defaultServiceConfig(Map) . 服务配置可以通过managedChannelBuilder.defaultServiceConfig(Map)指定。 You can choose to set different timeouts based on different methods.您可以根据不同的方法选择设置不同的超时时间。 Ideally this configuration would be managed by the service owner.理想情况下,此配置将由服务所有者管理。

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)));

Interceptors can be added to a stub via stub.withInterceptors() .拦截器可以通过stub.withInterceptors()添加到存根中。 Creating an interceptor that would add default timeouts would look like:创建一个添加默认超时的拦截器看起来像:

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM