此解决方案允许您配置一个可重用的功能,以便在不使用任何外部库的情况下基于特定异常进行重试
//创建一个适合你需要的函数。
@FunctionalInterface
public interface ThrowableBiFunction<U,T,R> {
R apply(U u ,T t) throws Exception;
}
//这是解决方案的关键
public interface ExceptionRetryable<T, U, R> {
int getRetries();
List<Class<? extends Exception>> getRetryableExceptions();
default R execute(ThrowableBiFunction<T, U, R> function, T t, U u) throws Exception {
int numberOfRetries = getRetries();
return execute(function, t, u, numberOfRetries);
}
default R execute(ThrowableBiFunction<T, U, R> function, T t, U u, int retryCount) throws Exception {
try {
log.info(" Attempting to execute ExceptionRetryable#execute ,Number of remaining retries {} ",retryCount);
return function.apply(t, u);
} catch (Exception e) {
log.info(" error occurred in ExceptionRetryable#execute",e);
if (retryCount == 0)
throw e;
for (Class exp : getRetryableExceptions()) {
if (e.getClass() == exp) {
return execute(function, t, u, retryCount - 1);
}
}
throw e;
}
}
}
//创建一个异常可重执行的实现
public class TestRetryable implements ExceptionRetryable<String, String, List<String>> {
@Override
public int getRetries() {
return 10;
}
@Override
public List<Class<? extends Exception>> getRetryableExceptions() {
return Arrays.asList(new Exception1().getClass(), new Exception2().getClass());
;
}
}
//最后创建一个throwablebiffunction,它封装了需要在exception上重试的代码段和ExceptionRetryable实例
TestRetryable retryable = new TestRetryable();
ThrowableBiFunction<Integer,Long, String> testRetrablefcn = { i, l ->
// your code goes here
};
Integer i = 0;
Long l = 1l;
String output = testRetrablefcn.execute(testRetrablefcn,i,l);