13

I am using @Retryable on a method like this :-

@Retryable( value = SQLException.class, 
      maxAttempts = 5, backoff = @Backoff(delay = 100))
void testMethod(String abc) throws SQLException{
//some method body that could throw sql exception
};

And i want to print the count of retry , with a message like :

Retry Number : 1
Retry Number : 2
...
Retry Number : 5

How can i achieve this ?

user1354825
  • 1,108
  • 4
  • 21
  • 54

2 Answers2

23

you can add below code:

@Retryable( value = SQLException.class, 
      maxAttempts = 5, backoff = @Backoff(delay = 100))
void testMethod(String abc) throws SQLException{
log.info("Retry Number : {}",RetrySynchronizationManager.getContext().getRetryCount());
};

RetrySynchronizationManager.getContext().getRetryCount() will give you the retry count on flow.

Velmurugan A
  • 348
  • 3
  • 7
13

you can add retryListener

    @Retryable( value = SQLException.class, maxAttempts = 5, 
                backoff = @Backoff(delay = 100), listeners = {"retryListener"})
    void testMethod(String abc) throws SQLException{
    //some method body that could throw sql exception
    };

retryListener should like below, you can print retry count on error.

@Slf4j
@Component
class RetryListener extends RetryListenerSupport {

    @Override
    public <T, E extends Throwable> void close(RetryContext context,
                                               RetryCallback<T, E> callback, Throwable throwable) {

        log.error("Unable to recover from  Exception");
        log.error("Error ", throwable);
        super.close(context, callback, throwable);
    }

    @Override
    public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
        log.error("Exception Occurred, Retry Count {} ", context.getRetryCount());
        super.onError(context, callback, throwable);
    }

    @Override
    public <T, E extends Throwable> boolean open(RetryContext context,
                                                 RetryCallback<T, E> callback) {
        log.error("Exception Occurred, Retry Session Started ");
        return super.open(context, callback);
    }
}
divilipir
  • 882
  • 6
  • 17
  • This listener is incorrect; the open method is not called when an "Exception Occurred"; it is called once, at the beginning; further, close does not mean "Unable to recover...", it is called at the end, regardless of outcome - see the Javadocs. The listener is called within the scope of the retry operation: `open -> call target one or more times until successful or retries exhausted -> close`. – Gary Russell Dec 21 '22 at 13:13