@FunctionInterFace
interface SimpleFunc<T>{
T exec();
}
public class RetryExecutor{
private static final Logger log = LOggerFactory.getLogger(RetryExecutor.class);
private static final int ATTEMPTS = 20;
private static final int SLEEP_UNIT = 200;
private final int maxAttempts;
public RetryExecutor(){
this(ATTEMPTS );
}
public RetryExecutor(int maxAttempts){
this.maxAttempts = maxAttempts;
}
public <T> void retry(SimpleFunc<T> func, Predicate<T> isOK ){
retryWithResult(func, isOK);
}
public <T> T retryWithResult(SimpleFunc<T> func, Predicate<T> isOK){
int times = 1;
while(times <= maxAttemps){
T ret = func.exec();
if (isOK.test(ret)){
return ret;
}else{
log.warn("retry " + times + " attemps, still unsatisfied!");
}
ThreadUtil.sleep(3000);
times++;
}
throw new MyException("retry failed with " + ATTEMPS + " attemps!");
}
}
具体使用:
直接将需要重试的方法传入retryWithResult即可。
retryExecutor.retryWithResult(getUserName(),Object::nonNull);
public String getUserName(){
return "haha";
}
这篇博客介绍了如何实现一个基于Java的重试执行器(RetryExecutor),该执行器用于在方法执行不满足特定条件时进行重试。通过`SimpleFunc`接口定义可执行操作,`Predicate`判断执行结果是否满足条件。在`retryWithResult`方法中,如果尝试达到最大次数(默认20次)仍不满足条件,则抛出自定义异常。示例展示了如何将一个获取用户名的方法包装在重试执行器中,确保返回值非空。
2489

被折叠的 条评论
为什么被折叠?



