Home > Software engineering >  @Retryable annotation not working for non Spring Bean class method
@Retryable annotation not working for non Spring Bean class method

Time:11-24

I am new to spring-retry. Basically, for retrying calls to REST APIs, I have integrated spring-retry into my spring-boot application. To do this, I have made following changes:

  1. Added spring-retry to pom.xml.

  2. Added following configuration:

    @Configuration
    @EnableRetry
    public class RetryConfiguration {
    }
    
  3. Finally added @Retryable annotation to the class (this class is not a Spring Bean) method that I would like to be retried for various exceptions as follows:

    public class OAuth1RestClient extends OAuthRestClient {
    
      @Override
      @Retryable(maxAttempts = 3, value = {
         Exception.class},
         backoff = @Backoff(delay = 100, multiplier = 3))
      public Response executeRequest(OAuthRequest request)
          throws InterruptedException, ExecutionException, IOException {
         System.out.println("Inside Oauth1 client");
         return myService.execute(request);
      }
    

Now, the executeRequest method is not retrying. I am not able to understand if I am missing anything here.

Could anyone please help? Thanks.

CodePudding user response:

If your class is not Spring managed (e.g. @Component/@Bean) the annotation processor for @Retryable won't pick it up.

You can always manually define a retryTemplate and wrap calls with it:

RetryTemplate.builder()
        .maxAttempts(2)
        .exponentialBackoff(100, 10, 1000)
        .retryOn(RestClientException.class)
        .traversingCauses()
        .build();

and then

retryTemplate.execute(context -> myService.execute(request));

If you want to retry on multiple exception, this can happen via custom RetryPolicy

Map<Class(? extends Throwable), Boolean> exceptionsMap = new HashMap<>();
exceptionsMap.put(InternalServerError.class, true);
exceptionsMap.put(RestClientException.class, true);

SimpleRetryPolicy policy = new SimpleRetryPolicy(5, exceptionsMap, true); 
RetryTemplate.builder()
        .customPolicy(policy)
        .exponentialBackoff(100, 10, 1000)
        .build();

FYI: RetryTemplate is blocking and you might want to explore a non-blocking async retry approach like async-retry. - and the retryOn() supports a list of exceptions.

  • Related