Spring / Spring Retry Interview Questions
How can you use Spring Retry with Spring WebClient or RestTemplate?
Spring Retry can wrap calls made through RestTemplate or WebClient to handle transient HTTP failures automatically. The approach differs slightly between the two due to their synchronous vs reactive nature.
With RestTemplate (synchronous) — using @Retryable:
@Service
public class OrderClient {
@Retryable(
retryFor = { HttpServerErrorException.class, ResourceAccessException.class },
maxAttempts = 3,
backoff = @Backoff(delay = 1000, multiplier = 2)
)
public OrderDto getOrder(Long id) {
return restTemplate.getForObject("/orders/" + id, OrderDto.class);
}
@Recover
public OrderDto recover(HttpServerErrorException ex, Long id) {
return OrderDto.fallback(id);
}
}With WebClient (reactive) — using reactor-retry or Mono.retryWhen:
webClient.get()
.uri("/orders/" + id)
.retrieve()
.bodyToMono(OrderDto.class)
.retryWhen(Retry.backoff(3, Duration.ofMillis(500))
.filter(ex -> ex instanceof WebClientResponseException.ServiceUnavailable));Note: @Retryable does not integrate naturally with reactive streams because it is designed for synchronous, blocking method calls. For reactive code, use Project Reactor's native Mono.retryWhen or Flux.retryWhen with reactor.util.retry.Retry.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
