如何使用@Retryable()
注解在spring-retry
中注册监听器?
@Bean
public RetryListener myRetryListener() {
return new MyRetryListener();
}
@Service
public class SampleService {
private int cnt = 1;
@Retryable(RuntimeException.class)
public void retryMethod(int x) throws Exception {
System.out.println("SampleService invoked.");
Thread.sleep(500);
if (cnt++ < 4) {
throw new RuntimeException("SampleService throwing exception");
}
}
}
如果我创建任何监听器 bean,它会自动注册到 RetryTemplate
。因此,如果我有多个监听器,那么如何让特定的监听器监听我的可重试服务?
最佳答案
我认为您正在寻找如下内容。 Retryable
注解有listeners参数(spring-retry:1.2.4.RELEASE
)
@Retryable(value = { Exception.class }, maxAttempts = 2, backoff = @Backoff(delay = 5000), listeners = "networkcallRetryLogListener")
List<ServiceObj> getDataFromThirdpartyService();
networkcallRetryLogListener
尝试登录我的案例。
public class NetworkcallRetryLogListener extends RetryListenerSupport {
private static final Logger LOG = LoggerFactory.getLogger(NetworkcallRetryLogListener.class);
@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
LOG.warn("Retry attempt {} for retryable method {} threw exception {}", context.getRetryCount(),
context.getAttribute("context.name"), ExceptionUtils.getStackTrace(throwable));
super.onError(context, callback, throwable);
}
}
希望对您有所帮助。
关于java - 将监听器注册到 spring 的 @Retryable 的注解方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47844432/