gpt4 book ai didi

Spring @Retryable - 调用时如何记录?

转载 作者:行者123 更新时间:2023-12-02 03:18:46 25 4
gpt4 key购买 nike

我使用 compile 'org.springframework.retry:spring-retry:1.2.2.RELEASE'Spring Boot 1.5.9.RELEASE

配置为重试我的方法,效果很好:

@Retryable(value = { IOException.class }, maxAttempts = 5, backoff = @Backoff(delay = 500))
public void someMethod(){...}

重试时如何输出一些特定的消息?

最佳答案

您可以注册一个RetryListener:

@Bean
public List<RetryListener> retryListeners() {
Logger log = LoggerFactory.getLogger(getClass());

return Collections.singletonList(new RetryListener() {

@Override
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
// The 'context.name' attribute has not been set on the context yet. So we have to use reflection.
Field labelField = ReflectionUtils.findField(callback.getClass(), "val$label");
ReflectionUtils.makeAccessible(labelField);
String label = (String) ReflectionUtils.getField(labelField, callback);
log.trace("Starting retryable method {}", label);
return true;
}

@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
log.warn("Retryable method {} threw {}th exception {}",
context.getAttribute("context.name"), context.getRetryCount(), throwable.toString());
}

@Override
public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
log.trace("Finished retryable method {}", context.getAttribute("context.name"));
}
});

如果您不需要从所有 3 个拦截点进行日志记录,则可以重写 RetryListenerSupport。例如:

@Bean
public List<RetryListener> retryListeners() {
Logger log = LoggerFactory.getLogger(getClass());

return Collections.singletonList(new RetryListenerSupport() {

@Override
public <T, E extends Throwable> void onError(
RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
log.warn("Retryable method {} threw {}th exception {}",
context.getAttribute("context.name"),
context.getRetryCount(), throwable.toString());
}
});
}

关于Spring @Retryable - 调用时如何记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49066706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com