Guava-retrying重试机制

转载于:https://blog.csdn.net/aitangyong/article/details/53889036

guava-retrying提供了WaitStrategy接口,用来控制2次重试的时间间隔,这个接口与StopStrategy有的类似。内置的等待策略在WaitStrategies中定义。



   
     
     
     
     
  1. import java.io.IOException;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. import java.util.concurrent.Callable;
  5. public class AlwaysExceptionTask implements Callable {
  6. private static final SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss,SSS");
  7. private int times = 1;
  8. @Override
  9. public Boolean call () throws Exception {
  10. System.out.println(df.format( new Date()));
  11. int thisTimes = times;
  12. times++;
  13. if (thisTimes == 1) {
  14. throw new NullPointerException();
  15. } else if (thisTimes == 2) {
  16. throw new IOException();
  17. } else if (thisTimes == 3) {
  18. throw new ArithmeticException();
  19. } else {
  20. throw new Exception();
  21. }
  22. }
  23. }


WaitStrategies.noWait()失败后立刻重试,没有等待时间。


   
     
     
     
     
  1. Retryer retryer = RetryerBuilder.newBuilder()
  2. .retryIfException()
  3. .withWaitStrategy(WaitStrategies.noWait())
  4. .build();
  5. System.out.println( "begin..." + df.format( new Date()));
  6. try {
  7. retryer.call( new AlwaysExceptionTask());
  8. } catch (Exception e) {
  9. System.err.println( "still failed after retry." + e.getCause().toString());
  10. }
  11. System.out.println( "end..." + df.format( new Date()));


WaitStrategies.fixedWait(1, TimeUnit.SECONDS)间隔固定时间之后重试,比如每隔1s重试一次。


   
     
     
     
     
  1. Retryer retryer = RetryerBuilder.newBuilder()
  2. .retryIfException()
  3. .withWaitStrategy(WaitStrategies.fixedWait( 1, TimeUnit.SECONDS))
  4. .build();
  5. System.out.println( "begin..." + df.format( new Date()));
  6. try {
  7. retryer.call( new AlwaysExceptionTask());
  8. } catch (Exception e) {
  9. System.err.println( "still failed after retry." + e.getCause().toString());
  10. }


WaitStrategies.randomWait(3, TimeUnit.SECONDS)间隔随机时间后重试,比如间隔0~3中随机时间后重试。


   
     
     
     
     
  1. Retryer retryer = RetryerBuilder.newBuilder()
  2. .retryIfException()
  3. .withWaitStrategy(WaitStrategies.randomWait( 3, TimeUnit.SECONDS))
  4. .build();
  5. System.out.println( "begin..." + df.format( new Date()));
  6. try {
  7. retryer.call( new AlwaysExceptionTask());
  8. } catch (Exception e) {
  9. System.err.println( "still failed after retry." + e.getCause().toString());
  10. }
  11. System.out.println( "end..." + df.format( new Date()));


WaitStrategies.randomWait(2, TimeUnit.SECONDS, 5, TimeUnit.SECONDS)最小值,最大值之间的随机时间。


   
     
     
     
     
  1. Retryer retryer = RetryerBuilder.newBuilder()
  2. .retryIfException()
  3. .withWaitStrategy(WaitStrategies.randomWait( 2, TimeUnit.SECONDS, 5, TimeUnit.SECONDS))
  4. .build();
  5. System.out.println( "begin..." + df.format( new Date()));
  6. try {
  7. retryer.call( new AlwaysExceptionTask());
  8. } catch (Exception e) {
  9. System.err.println( "still failed after retry." + e.getCause().toString());
  10. }
  11. System.out.println( "end..." + df.format( new Date()));




WaitStrategies.incrementingWait增量重试,重试的次数越多,等待时间间隔越长。incrementingWait需要传递2个参数,一个是initialSleepTime(第一次到第二次尝试的间隔),一个是increment(每增加一次尝试,需要增加的时间间隔)。第一次尝试是不需要等待的,因为guava-retrying中的第一次尝试,对应正常的第一次调用。从第二次重试开始,第n-1次到n次间隔是:initialSleepTime + (n-2)*increment。

1、WaitStrategies.incrementingWait(0, TimeUnit.SECONDS, 0, TimeUnit.SECONDS)等价于     WaitStrategies.noWait()。

2、 WaitStrategies.incrementingWait(1, TimeUnit.SECONDS, 0, TimeUnit.SECONDS)等价于WaitStrategies.fixedWait(1, TimeUnit.SECONDS)

3、 WaitStrategies.incrementingWait(0, TimeUnit.SECONDS, 1, TimeUnit.SECONDS)等价于WaitStrategies.fixedWait(1, TimeUnit.SECONDS)。


4、  WaitStrategies.incrementingWait(1, TimeUnit.SECONDS, 1, TimeUnit.SECONDS)



WaitStrategies.fibonacciWait()按照斐波那契数列等待。fibonacciWait(long multiplier,long maximumTime,TimeUnit maximumTimeUnit),multiplier单位固定是ms,maximumTime最大等待时间。n=1的时候,是无需等待的。当n>=2的时候,开始符合斐波那契数列。n=2的时候,等待1 * multiplier毫秒;n=3的时候,等待1 * multiplier毫秒;n=4的时候,等待2 * multiplier毫秒;n=5的时候,等待3 * multiplier毫秒;n=6的时候,等待5 * multiplier毫秒;n=7的时候,等待8 * multiplier毫秒;n=8的时候,等待15 * multiplier毫秒;......但是等待时间最长不超过maximumTime。


   
     
     
     
     
  1. Retryer retryer = RetryerBuilder.newBuilder()
  2. .retryIfException()
  3. .withWaitStrategy(WaitStrategies.fibonacciWait( 100, 10, TimeUnit.SECONDS))
  4. .build();
  5. System.out.println( "begin..." + df.format( new Date()));
  6. try {
  7. retryer.call( new AlwaysExceptionTask());
  8. } catch (Exception e) {
  9. System.err.println( "still failed after retry." + e.getCause().toString());
  10. }


WaitStrategies.exponentialWait按照指数递增(2的n次方)来等待,各个参数含义与fibonacciWait相同。


   
     
     
     
     
  1. Retryer retryer = RetryerBuilder.newBuilder()
  2. .retryIfException()
  3. .withWaitStrategy(WaitStrategies.exponentialWait( 100, 10, TimeUnit.SECONDS))
  4. .build();
  5. System.out.println( "begin..." + df.format( new Date()));
  6. try {
  7. retryer.call( new AlwaysExceptionTask());
  8. } catch (Exception e) {
  9. System.err.println( "still failed after retry." + e.getCause().toString());
  10. }


WaitStrategies.exceptionWait根据抛出的异常来决定等待的时间长短,没有什么实际用处,不过作为学习还是可以了解下,说不定将来能排上用场呢。下面我们定义1个任务,随机抛出不同异常。


   
     
     
     
     
  1. class RandomExceptionTask implements Callable {
  2. @Override
  3. public Boolean call () throws Exception {
  4. int round = ( int) Math.floor(Math.random() * 8);
  5. System.out.println( "round=" + round + ",time=" + df.format( new Date()));
  6. if (round == 1) {
  7. throw new NullPointerException();
  8. } else if (round == 2) {
  9. throw new IOException();
  10. } else if (round == 3) {
  11. throw new ArithmeticException();
  12. } else if (round == 4) {
  13. throw new IllegalStateException();
  14. } else if (round == 5) {
  15. throw new IndexOutOfBoundsException();
  16. } else {
  17. return true;
  18. }
  19. }
  20. }


如果我 们希望实现这种效果:如果出现了 NullPointerException,那么等待1s后再重试;如果抛出IOException,那等待2s后再重试;如果出现了ArithmeticException,那么等待3s后再重试;如果出现了IllegalStateException,那么等待4s后再重试;如果出现了IndexOutOfBoundsException,那么等待5s后再重试;否则不等待,立刻重试。

   
     
     
     
     
  1. // 根据不同异常,等待不同时间后重试
  2. private static extends Throwable> Function itsFunction (Class exceptionClass) {
  3. Function result = new Function() {
  4. @Nullable
  5. @Override
  6. public Long apply (@Nullable T input) {
  7. if (input instanceof NullPointerException) {
  8. return 1 * 1000L;
  9. } else if (input instanceof IOException) {
  10. return 2 * 1000L;
  11. } else if (input instanceof ArithmeticException) {
  12. return 3 * 1000L;
  13. } else if (input instanceof IllegalStateException) {
  14. return 4 * 1000L;
  15. } else if (input instanceof IndexOutOfBoundsException) {
  16. return 5 * 1000L;
  17. } else {
  18. return 0L;
  19. }
  20. }
  21. };
  22. return result;
  23. }


下面是测试代码,可以看出不同的异常确实会导致不同的重试间隔。


   
     
     
     
     
  1. WaitStrategy exceptionJoin = WaitStrategies.join(
  2. WaitStrategies.exceptionWait(NullPointerException.class, itsFunction(NullPointerException.class)),
  3. WaitStrategies.exceptionWait(IOException.class, itsFunction(IOException.class)),
  4. WaitStrategies.exceptionWait(ArithmeticException.class, itsFunction(ArithmeticException.class)),
  5. WaitStrategies.exceptionWait(IllegalStateException.class, itsFunction(IllegalStateException.class)),
  6. WaitStrategies.exceptionWait(IndexOutOfBoundsException.class, itsFunction(IndexOutOfBoundsException.class))
  7. );
  8. Retryer retryer = RetryerBuilder.newBuilder()
  9. .retryIfException()
  10. .withWaitStrategy(exceptionJoin)
  11. .build();
  12. System.out.println( "begin..." + df.format( new Date()));
  13. try {
  14. retryer.call( new RandomExceptionTask());
  15. } catch (Exception e) {
  16. System.err.println( "still failed after retry." + e.getCause().toString());
  17. }
  18. System.out.println( "end..." + df.format( new Date()));



你可能感兴趣的:(JAVA,frame,java)