Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print retry count with @Retryable

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 ?

like image 626
user1354825 Avatar asked Dec 06 '25 15:12

user1354825


2 Answers

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.

like image 168
Velmurugan A Avatar answered Dec 08 '25 03:12

Velmurugan A


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..");
    }

    // 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());
    }

    // 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 true;
    }
}
like image 31
divilipir Avatar answered Dec 08 '25 03:12

divilipir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!