1

I want to implement retry mechanism and I did something like this:

  public static final Retry fixedRetry = Retry.fixedDelay(3, Duration.ofSeconds(5))
      .onRetryExhaustedThrow(
          (retryBackoffSpec, retrySignal) -> new TimeoutException(
              retrySignal.failure().getMessage()));

And used this method here:

 public List<A> findByTimestamp(LocalDate localDate) {
    return webClient.get()
        .uri(bProp.getPath())
        .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
        .retrieve()
        .bodyToFlux(bData.class)
        .retryWhen(fixedRetry)
        .map(this::toC)
        .collectList()
        .block();
  }

But I want to create a generic one to use it across all application to not write first method in all classes, how can I do this more efficiently?

n1cula
  • 87
  • 1
  • 9

2 Answers2

0

I'd register the webClient as a bean in a configuration class and implement the retry logic there and then autowire it where you need the webClient instead of creating a new object explicitly. I found an answer to a similiar question that might be helpful.

I don't have time to check if this code works but I mean something along these lines:

@Configuration
public class WebClientConfiguration {

@Bean
public WebClient retryWebClient(WebClient.Builder builder) {
    return builder.baseUrl("http://localhost:8080")
            .filter((request, next) -> next.exchange(request)
                    .retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(5))
                            .onRetryExhaustedThrow(
                                    (retryBackoffSpec, retrySignal) -> new TimeoutException(
                                            retrySignal.failure().getMessage()))))
            .build();
}
}

And then just autowire it anywhere you need:

@Autowired
private WebClient webClient;
mklepa
  • 211
  • 3
  • 7
  • Can I somehow create a class with only the fixedRetry method to pass it in my second method? – n1cula Sep 24 '20 at 09:55
0

The way that I decided to implement this is as follows:

public class RetryWebClient {

  public static final Retry fixedRetry = Retry.fixedDelay(3, Duration.ofSeconds(5))
      .onRetryExhaustedThrow(
          (retryBackoffSpec, retrySignal) -> new TimeoutException(
              retrySignal.failure().getMessage()));

  private RetryWebClient() {}

}

And called it in retryWhen:

.retryWhen(RetryWebClient.fixedRetry)
n1cula
  • 87
  • 1
  • 9
  • Cool, I hope I was able to help. I'm not 100% sure that making fixedRetry static and passing it to bean creation method is ok (I assume that's what you're doing), but it should be fine since the default scope is a singleton. – mklepa Oct 02 '20 at 09:03