Reputation: 597
I'm trying to find the best way to combine Spring 5 WebClient
and Hystrix
. Using Hystrix, I set different timeouts for different type of requests done by the WebClient
.
When Hystrix
reaches it's timeout, I also want to make sure that WebClient
closes its connection. Previously when using AsyncHttpClient
, this was done by setting a requestTimeout
before performing the specific call. However, setting the request timeout on WebClient
is much more complicated and needs to be done on the ClientHttpConnector
according to this answer.
Brian Cozel mentions that it is optimal to share the same ClientHttpConnector
throughout the application. However, because the request specific timeout needs to be set on the ClientHttpConnector
, this does not seem possible.
In Spring's Reactive WebClient
, is there a proper way to set request specific timeouts, but still use a single ClientHttpConnector
?
Upvotes: 4
Views: 3320
Reputation: 59211
The timeout operations that you can configure on the client connector are quite low level: they're about socket/connection timeouts. This configuration cannot be done at the request level, since connections might be shared and reused in a connection pool.
This question is about response timeouts, since you seem to care about the amount of time to get the response, on a per request basis.
In this case, you can use the timeout
operator on a per request basis:
Mono<UserData> result = this.webClient.get()
.uri("/user")
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(UserData.class)
.timeout(Duration.ofSeconds(10));
The timeout operator will throw a TimeoutException
in the pipeline; you can use one of the onError*
operators to define what should be done in those cases. Alternatively, you can directly use the timeout(Duration, Mono)
variant that provides a fallback.
Upvotes: 3