Java簡単な再試行キット

8821 ワード

インタフェース呼び出しでは様々な理由で失敗したタスクがリセットされる可能性があり、Guava-Retryingを使用すると再試行機能を容易に実現できます.
まず、Guava-Retryingのパッケージを参照する必要があります

com.github.rholder
guava-retrying
2.0.0

コードの例:
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.google.common.base.Predicates;

import java.util.concurrent.TimeUnit;

import static com.github.rholder.retry.WaitStrategies.incrementingWait;

/**
 * @author wangxuexing
 * @descrption
 * @date
 */
public class RetryDemo {
    public static void main(String[] args) {
        Retryer retryer = RetryerBuilder.newBuilder().
                                    //       
                                    retryIfException().
                                    //     false   
                                    retryIfResult(Predicates.equalTo(false)).
                                    //    
                                    withWaitStrategy(incrementingWait(30, TimeUnit.SECONDS, 30, TimeUnit.SECONDS)).
                                    //    
                                    withStopStrategy(StopStrategies.stopAfterAttempt(3)).
                                    //    
                                    withRetryListener(new MyRetryListener()).build();
        try {
            retryer.call(new TaskCallable());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 
TaskCallableはタスクの具体的な実装クラスであり、Callableインタフェースを実現している.
 
import java.util.concurrent.Callable;

/**
 * @author wangxuexing
 * @descrption
 * @date
 */
public class TaskCallable implements Callable {

    public Boolean call() throws Exception {
        return false;
    }
}
  ,MyRetryListener     RetryListener  ,             
import com.github.rholder.retry.Attempt;
import com.github.rholder.retry.RetryListener;

/**
 * @author wangxuexing
 * @descrption
 * @date
 */
public class MyRetryListener implements RetryListener {
    public  void onRetry(Attempt attempt) {
        System.out.print("[retry]time=" + attempt.getAttemptNumber());
        //           
        System.out.print(",delay=" + attempt.getDelaySinceFirstAttempt());

        //     :      ,       
        System.out.print(",hasException=" + attempt.hasException());
        System.out.print(",hasResult=" + attempt.hasResult());

        //          
        if (attempt.hasException()) {
            System.out.print(",causeBy=" + attempt.getExceptionCause().toString());
        } else {//         
            System.out.print(",result=" + attempt.getResult());
        }
        System.out.println();
    }
}

mainメソッドを実行すると、実行結果が表示されます.
[retry]time=1,delay=0,hasException=false,hasResult=true,result=false
[retry]time=2,delay=30000,hasException=false,hasResult=true,result=false
[retry]time=3,delay=90000,hasException=false,hasResult=true,result=false
com.github.rholder.retry.RetryException: Retrying failed to complete successfully after 3 attempts.
	at com.github.rholder.retry.Retryer.call(Retryer.java:174)
	at test.retryer.RetryDemo.main(RetryDemo.java:32)

  
以下、詳しく分析します.
RetryerBuilderはfactory作成者で、再試行ソースの設定をカスタマイズでき、複数の再試行ソースをサポートできます.再試行回数または再試行タイムアウト時間を構成できます.また、待機時間間隔を構成し、再試行者Retryerインスタンスを作成できます.
RetryerBuilderの再試行ソースは、Exception例外オブジェクトとカスタムブレークスルーオブジェクトをサポートし、retryIfExceptionとretryIfResultの設定により、複数の互換性をサポートします.retryIfExceptionでは、runtime異常、checked異常を投げ出すと再試行されますが、errorを投げ出すと再試行されません.retryIfRuntimeExceptionはruntime異常を投げたときにのみ再試行され、checked異常もerrorも再試行されません.retryIfExceptionOfTypeでは、Null PointerExceptionやIllegalStateExceptionなど、特定の例外が発生した場合にのみ再試行できます.たとえば、Null PointerExceptionやIllegalStateExceptionはruntime例外に属します.カスタムerrorretryIfResultでは、Callableメソッドを指定して値を返すときに再試行できます.
StopStrategy:再試行ポリシーを停止し、3つを提供します.StopAfterDelayStrategyは最長許容実行時間を設定します.例えば、最大実行10 sを設定し、タスク実行回数にかかわらず、再試行時に最大時間を超えた場合、タスクは終了し、再試行異常RetryExceptionに戻る.NeverStopStrategyは停止せず、所望の結果を返すことを常に輪訓して知る必要がある場合に使用されます.
StopAfterAttemptStrategyは最大再試行回数を設定し、最大再試行回数を超えると再試行を停止し、再試行異常を返します.
WaitStrategy:待ち時間ポリシー(制御間隔)で、次回の実行時間:FixedWaitStrategy固定待ち時間ポリシーを返します.RandomWaitStrategyランダム待ち時間ポリシー(最小時間と最大時間を指定できます.待ち時間はその区間ランダム値です).IncrementingWaitStrategyは待ち時間ポリシーを増加します.(再試行回数とともに待機時間が増加する初期値とステップを指定します).ExponentialWaitStrategy指数待ち時間ポリシー.F i b o n acciWaitStrategy Fibonacci待ち時間ポリシー.ExceptionWaitStrategy異常時間待ちポリシー.CompositeWaitStrategy複合時間待ちポリシー.