Skip to content

Instantly share code, notes, and snippets.

@umit
Last active May 29, 2018 15:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umit/6f256699d710a8183a663796a2ecd5af to your computer and use it in GitHub Desktop.
Save umit/6f256699d710a8183a663796a2ecd5af to your computer and use it in GitHub Desktop.
RetryRestTemplate
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.retry.Retry;
import reactor.retry.RetryExhaustedException;
import java.time.Duration;
import java.util.function.Supplier;
@Component
public class RetryRestTemplate {
public <T> T execute(Mono<T> source) {
Mono<T> defer = Mono.defer(() -> source.subscribeOn(Schedulers.elastic()));
Retry<T> retry = Retry.<T>anyOf(RuntimeException.class).exponentialBackoff(Duration.ofMillis(250), Duration.ofMillis(5000)).timeout(Duration.ofMillis(60000));
return defer
.publishOn(Schedulers.parallel())
.retryWhen(retry)
.onErrorMap(t -> t instanceof RetryExhaustedException, Throwable::getCause).single().block();
}
public <T> Mono<T> executeWithSupplier(Supplier<T> supplier, RetryConfig retryConfig) {
Mono<T> defer = Mono.defer(() -> Mono.just(supplier.get()));
Retry<T> retry = Retry.<T>anyOf(RuntimeException.class)
.exponentialBackoff(Duration.ofMillis(retryConfig.firstBackoff), Duration.ofMillis(retryConfig.maxBackoff))
.timeout(Duration.ofMillis(retryConfig.maxBackoff));
return defer
.publishOn(Schedulers.parallel())
.retryWhen(retry)
.onErrorMap(t -> t instanceof RetryExhaustedException, Throwable::getCause);
}
}
@umit
Copy link
Author

umit commented May 29, 2018

Usage :

retryRestTemplate.execute(Mono.fromCallable(() -> restTemplate.getForObject("http://www.abc.com/xyz", String.class)));

@umit
Copy link
Author

umit commented May 29, 2018

Usage:

RetryConfig retryConfig = new RetryConfig();
retryConfig.setFirstBackoff(250);
retryConfig.setMaxBackoff(5000);
retryConfig.setTimeout(60000);

retryRestTemplate.executeWithSupplier(() -> restTemplate.getForObject("http://www.xyz.com/abc", String.class), retryConfig).single().block(); 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment