Created
October 9, 2023 02:29
-
-
Save anadimisra/d8b4ab5ca882c65d59c1338c35c803da to your computer and use it in GitHub Desktop.
Retires with exponential backup using Spring WebFlux WebClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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