@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";
}