微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用@Retryable打印重试计数

如何解决使用@Retryable打印重试计数

我在类似这样的方法上使用@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

我该如何实现?

解决方法

您可以添加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如下所示,您可以在错误时打印重试计数。

@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,Throwable throwable) {
        log.error("Exception Occurred,Retry Count {} ",context.getRetryCount());
        super.onError(context,E extends Throwable> boolean open(RetryContext context,E> callback) {
        log.error("Exception Occurred,Retry Session Started ");
        return super.open(context,callback);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。