本文介绍了Spring @Retryable - 如何在调用时记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 compile 'org.springframework.retry:spring-retry:1.2.2.RELEASE' 和 Spring Boot 1.5.9.RELEASE.
配置为重试我的方法,效果很好:
Configured to retry my method and it works well:
@Retryable(value = { IOException.class }, maxAttempts = 5, backoff = @Backoff(delay = 500)) public void someMethod(){...}重试时如何输出一些特定的消息?
How to output some specific message when retry occurs?
推荐答案您可以注册一个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.例如:
If you don't need to log from all 3 interception points, you can override RetryListenerSupport instead. For example:
@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
发布评论