Spring @Retryable

编程入门 行业动态 更新时间:2024-10-20 07:48:46
本文介绍了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

本文发布于:2023-10-24 14:06:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524134.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Spring   Retryable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!