1.第一种情况 :
抛出指定的异常IOException 则继续执行,若不是则抛出异常终止程序
package com.qimh.demo2;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class RetryDemo {
private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
public static void main(String[] args) throws Exception {
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
//抛出指定的异常IOException 则继续执行,若不是则抛出异常终止程序
.retryIfExceptionOfType(IOException.class)
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
.withStopStrategy(StopStrategies.stopAfterAttempt(5))
.build();
System.out.println("begin..." + df.format(new Date()));
try {
retryer.call(buildTask());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("end..." + df.format(new Date()));
}
private static Callable<Boolean> buildTask() {
return new Callable<Boolean>() {
private int i = 0;
@Override
public Boolean call() throws Exception {
System.out.println("called");
i++;
if (i == 1) {
throw new IOException();
} else {
throw new NullPointerException();
}
}
};
}
}
2.第二种情况:
RetryException就很简单了,当所有重试结束后,依然不能成功,那么就会抛这异常。
package com.qimh.demo2;
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class RetryDemo2 {
private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss,SSS");
public static void main(String[] args) throws Exception {
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
//RetryException就很简单了,当所有重试结束后,依然不能成功,那么就会抛这异常。
.retryIfException()
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))
.withStopStrategy(StopStrategies.stopAfterAttempt(5))
.build();
System.out.println("begin..." + df.format(new Date()));
try {
retryer.call(buildTask());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("end..." + df.format(new Date()));
}
private static Callable<Boolean> buildTask() {
return new Callable<Boolean>() {
private int i = 0;
@Override
public Boolean call() throws Exception {
System.out.println("called");
i++;
if (i == 1) {
throw new IOException();
} else {
throw new NullPointerException();
}
}
};
}
}
参考连接:https://blog.csdn.net/aitangyong/article/details/53894997