Print retry count with @Retryable

14.4k views Asked by At

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 ?

3

There are 3 answers

1
Velmurugan A On BEST ANSWER

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.

2
divilipir On

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 MyRetryListener implements RetryListener {

    // Called after the final attempt (succesful or not).
    @Override
    public <T, E extends Throwable> void close(RetryContext context,
                                               RetryCallback<T, E> callback, Throwable throwable) {

        log.debug("Retry closing..");
        super.close(context, callback, throwable);
    }

    // Called after every unsuccessful attempt at a retry
    @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);
    }

    // Called before the first attempt in a retry
    @Override
    public <T, E extends Throwable> boolean open(RetryContext context,
                                                 RetryCallback<T, E> callback) {
        log.debug("Retry opening..");
        return super.open(context, callback);
    }
}
0
rolanb On

You can also enable logging for 'org.springframework.retry' package

application.yml

logging:
  level:
    org.springframework:
      retry: DEBUG