Java重試模塊抽象

/**
 *
 * @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 {
        // 如果e滿足某些條件,則進行重試機制;
        if(isNeedToRetry(exp)) {
            // 先休眠1s鍾;
            goToSleepOneSeconds();
            // time 自增
            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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章