Skip to content

Instantly share code, notes, and snippets.

@anadimisra
Created October 9, 2023 02:29
Show Gist options
  • Save anadimisra/d8b4ab5ca882c65d59c1338c35c803da to your computer and use it in GitHub Desktop.
Save anadimisra/d8b4ab5ca882c65d59c1338c35c803da to your computer and use it in GitHub Desktop.
Retires with exponential backup using Spring WebFlux WebClient
webClient.get().uri(uri)
.headers(headers -> headers.addAll(httpHeaders))
.retrieve()
.bodyToMono(new ParameterizedTypeReference<Map<String, Object>>() {
})
.log(this.getClass().getName(), Level.FINE)
.retryWhen(
Retry.backoff(3, Duration.ofSeconds(2))
.jitter(0.7)
.filter(throwable -> throwable instanceof RuntimeException ||
(throwable instanceof WebClientResponseException &&
(((WebClientResponseException) throwable).getStatusCode() == HttpStatus.GATEWAY_TIMEOUT || ((WebClientResponseException) throwable).getStatusCode() == HttpStatus.SERVICE_UNAVAILABLE || ((WebClientResponseException) throwable).getStatusCode() == HttpStatus.BAD_GATEWAY)))
.onRetryExhaustedThrow((retryBackoffSpec, retrySignal) -> {
log.error("Service at {} failed to respond, after max attempts of: {}", uri, retrySignal.totalRetries());
return retrySignal.failure();
}))
.onErrorResume(WebClientResponseException.class, ex -> ex.getStatusCode().is4xxClientError() ? Mono.empty() : Mono.error(ex));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment