Java 8 实现一个简单的错误重试工具类
首先实现这个工具类需要熟悉一下Java 8的函数式编程或者对匿名内部类的实现方式
知识储备:
最好熟悉一下 Java 8 函数式编程一些常见的函数式接口,比如:Consumer/Supplier …
因为使用 Lambda 实现相对实现内部类的方式更加简洁和直观
代码实现:
这个工具类的实现非常的简单,现在直接上代码:
import java.util.List;
import java.util.function.Consumer;
/**
* 错误重试工具类
*
* @author hdfg159
* @date 2020/8/4 23:27
*/
public abstract class RetryUtils {
/**
* 重试调度方法
*
* @param dataSupplier
* 返回数据方法执行体
* @param exceptionCaught
* 出错异常处理(包括第一次执行和重试错误)
* @param retryCount
* 重试次数
* @param sleepTime
* 重试间隔睡眠时间(注意:阻塞当前线程)
* @param expectExceptions
* 期待异常(抛出符合相应异常时候重试),空或者空容器默认进行重试
* @param <R>
* 数据类型
*
* @return R
*/
public static <R> R invoke(Supplier<R> dataSupplier, Consumer<Throwable> exceptionCaught, int retryCount, long sleepTime, List<Class<? extends Throwable>> expectExceptions) {
Throwable ex;
try {
// 产生数据
return dataSupplier == null ? null : dataSupplier.get();
} catch (Throwable throwable) {
// 捕获异常
catchException(exceptionCaught, throwable);
ex = throwable;
}
if (expectExceptions != null && !expectExceptions.isEmpty()) {
// 校验异常是否匹配期待异常
Class<? extends Throwable> exClass = ex.getClass();
boolean match = expectExceptions.stream().anyMatch(clazz -> clazz == exClass);
if (!match) {
return null;
}
}
// 匹配期待异常或者允许任何异常重试
for (int i = 0; i < retryCount; i++) {
try {
if (sleepTime > 0) {
Thread.sleep(sleepTime);
}
return dataSupplier.get();
} catch (InterruptedException e) {
System.err.println("thread interrupted !! break retry,cause:" + e.getMessage());
// 恢复中断信号
Thread.currentThread().interrupt();
// 线程中断直接退出重试
break;
} catch (Throwable throwable) {
catchException(exceptionCaught, throwable);
}
}
return null;
}
private static void catchException(Consumer<Throwable> exceptionCaught, Throwable throwable) {
try {
if (exceptionCaught != null) {
exceptionCaught.accept(throwable);
}
} catch (Throwable e) {
log.error("retry exception caught throw error:{}", e.getMessage());
}
}
/**
* 函数式接口可以抛出异常
*
* @param <T>
*/
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*
* @throws Exception 错误时候抛出异常
*/
T get() throws Exception;
}
}
附上一个简单的测试用例和用法:
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
String error = RetryUtils.invoke(() -> {
// 返回数据的代码编写
// return "test";
throw new RuntimeException("error");
}, throwable -> System.out.println("error"), 3, 5_000, new ArrayList<>());
// 输出返回数据
System.out.println(error);
}
}
温馨提示
用 RxJava
的同学可以使用 Retry
操作符实现同样的功能哦,RxJava
是非常强大操作符工具
工具类优化
以前的工具类难以满足需求,而且有缺陷,现在更新一下
主要优化点
-
对异常重试的判断,不在固定异常列表重试
-
对重试异常处理的优化,重试只针对异常重试的判断,不是无脑重试
-
不支持非运行时异常
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* @author hdfg159
* @since 2024/6/19 16:51
*/
@Slf4j
public abstract class RetryUtils {
public static <R> R invoke(Supplier<R> dataSupplier,
Consumer<Throwable> exceptionCaught,
int retryCount,
long sleepTime,
Predicate<Throwable> exceptionFilter) {
Exception finalException = null;
var maxCount = retryCount + 1;
for (int count = 1; count <= maxCount; count++) {
try {
return (dataSupplier == null) ? null : dataSupplier.get();
} catch (Exception e) {
finalException = e;
if (count >= maxCount) {
throw e;
}
if (!exceptionFilter.test(e)) {
throw e;
}
catchException(exceptionCaught, e);
}
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
log.error("Thread interrupted,break retry:{}", count);
Thread.currentThread().interrupt();
throw new RetryFailException(finalException, count);
}
}
}
throw new RetryFailException(finalException, maxCount);
}
private static void catchException(Consumer<Throwable> exceptionCaught, Throwable throwable) {
try {
if (exceptionCaught != null) {
exceptionCaught.accept(throwable);
}
} catch (Exception e) {
log.error("Retry exception caught throw:{}", e.getMessage());
}
}
@Getter
public static class RetryFailException extends RuntimeException {
private final int retryCount;
public RetryFailException(Throwable cause, int retryCount) {
super(cause);
this.retryCount = retryCount;
}
}
}
后续优化方向
工具类还是不够好用,大家可以尝试往下面几方面优化:
- 支持重试上下文,每次重试传递数据
- 重试时间间隔优化,可以根据不同数据或者不同次数产生不同重试间隔时间