Spring Boot 使用@Retryable打印重试次数

8mmmxcuj  于 5个月前  发布在  Spring
关注(0)|答案(2)|浏览(127)

我在这样的方法上使用@Retryable:

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

字符串
我想打印重试次数,并显示如下消息:

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


我如何才能做到这一点?

5tmbdcev

5tmbdcev1#

你可以添加下面的代码:

@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()将给予流的重试计数。

agyaoht7

agyaoht72#

可以添加重试

@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
    };

字符串
重试计数应该像下面这样,你可以打印重试计数错误。

@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);
    }
}

相关问题