我将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(){...}
重试时如何输出某些特定消息?
答案 0 :(得分:8)
您可以注册for-yield
:
RetryListener
如果您不需要从所有3个拦截点登录,则可以覆盖@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"));
}
});
。例如:
RetryListenerSupport
答案 1 :(得分:3)
查看代码,org.springframework.retry.support.RetryTemplate
执行重试逻辑以重试操作。此模板仅记录以下简单内容:
o.s.retry.support.RetryTemplate : Retry: count=0
o.s.retry.support.RetryTemplate : Checking for rethrow: count=1
o.s.retry.support.RetryTemplate : Retry: count=1
o.s.retry.support.RetryTemplate : Checking for rethrow: count=2
o.s.retry.support.RetryTemplate : Retry: count=2
o.s.retry.support.RetryTemplate : Checking for rethrow: count=3
o.s.retry.support.RetryTemplate : Retry failed last attempt: count=3
如果要记录特定的异常,可以捕获异常日志并重新抛出。不幸的是,据我所知,没有办法在框架内记录自定义消息。
另一种方法是遮蔽负责调用方法的实际拦截器,如RetryOperationsInterceptor
,但不建议这样做。