I am looking for a way to increase the duration of the timeout after successive retries on webclient calls.
For example, I want the first request to timeout after 50ms, the first retry will then timeout after 500ms, and a second and final retry to have a timeout duration of 5000ms.
I am not sure how to go about doing this. I am only aware of how to set the timeout value to a fixed duration for all retries.
ex.
public Flux<Employee> findAll()
{
return webClient.get()
.uri("/employees")
.retrieve()
.bodyToFlux(Employee.class)
.timeout(Duration.ofMillis(50))
.retry(2);
}
You can abstract out your backoff & timeout logic into a separate utility function, then simply call transform() on your publisher.
In your case, it looks like you're after basic backoff functionality - take an initial timeout value, then multiply it by a factor until we reach a maximum. We can implement this like so:
public <T> Flux<T> retryWithBackoffTimeout(Flux<T> flux, Duration timeout, Duration maxTimeout, int factor) {
return mono.timeout(timeout)
.onErrorResume(e -> timeout.multipliedBy(factor).compareTo(maxTimeout) < 1,
e -> retryWithBackoffTimeout(mono, timeout.multipliedBy(factor), maxTimeout, factor));
}
...but this can of course be any kind of timeout logic you like.
With that utility function in place, your findAll() method becomes:
public Flux<Employee> findAll()
{
return webClient.get()
.uri("/employees")
.retrieve()
.bodyToFlux(Employee.class)
.transform(m -> retryWithBackoffTimeout(m, Duration.ofMillis(50), Duration.ofMillis(500), 10));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With