Reputation: 405
I am trying to start using grpc for Android.
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
Upvotes: 3
Views: 6809
Reputation: 26454
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)
. 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()
. 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());
Upvotes: 5