san*_*nit 10 java spring-retry
如何spring-retry使用@Retryable()注解注册监听器?
@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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我创建任何侦听器 bean,它会自动注册到RetryTemplate. 因此,如果我有多个侦听器,那么如何要求特定侦听器侦听我的可重试服务?
我认为您正在寻找类似下面的东西。Retryable注解有监听器参数( spring-retry:1.2.4.RELEASE)
@Retryable(value = { Exception.class }, maxAttempts = 2, backoff = @Backoff(delay = 5000), listeners = "networkcallRetryLogListener")
List<ServiceObj> getDataFromThirdpartyService();
Run Code Online (Sandbox Code Playgroud)
并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);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助。
spring-retry 的官方 Github 存储库中有一个非常古老的拉取请求,它似乎可以实现您想要做的事情。
https://github.com/spring-projects/spring-retry/pull/77