/**
*
* @author claireliu
* @date 2017/12/20
*/
public interface RetryProcessor<T> {
T process() throws TimeoutException;
}
/**
*
* @author claireliu
* @date 2017/12/20
*/
public class SomeRetryTemplate {
int TRY_TIMES = 3;
public <T> T process(RetryProcessor<T> processor) throws TimeoutException{
int time = 1;
TimeoutException exp = null;
while (time <= TRY_TIMES) {
try{
return processor.process();
}catch (TimeoutException e) {
exp = e;
time = handleExp(time, e);
}
}
throwExpAfterMoreThanMaxTryTimes(time, exp);
return null;
}
/**
* 处理exception的情况。
*/
private int handleExp(int time, TimeoutException exp) throws TimeoutException {
if(isNeedToRetry(exp)) {
goToSleepOneSeconds();
time++;
}else {
throw exp;
}
return time;
}
/**
* 当超过TRY_TIMES也退出。
*/
private void throwExpAfterMoreThanMaxTryTimes(int time, TimeoutException exp) throws TimeoutException {
if(time > TRY_TIMES) {
throw exp;
}
}
private void goToSleepOneSeconds() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private boolean isNeedToRetry(TimeoutException exp) {
return false;
}
}
/**
*
* @author claireliu
* @date 2017/12/20
*/
public class RetryMain {
public static void main(String[] args) throws TimeoutException {
SomeRetryTemplate template = new SomeRetryTemplate();
template.process(new RetryProcessor<Boolean>() {
@Override
public Boolean process() throws TimeoutException {
return doSomeBusinessAction();
}
});
}
private static Boolean doSomeBusinessAction() throws TimeoutException {
throw new TimeoutException();
}
}