1:在与外部接口通信的时候,如对接第三方系统,一般情况不知道http协议是否成功,最好加上重试。
spring-retry提供了相关代码。
新增pom
org.springframework.retry spring-retry
新增service
@Service
public class TestService {
private int code = 0;
@Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 1000,multiplier = 1.5))
public int test() throws Exception{
// code++;
// if (code % 3 != 0){
// throw new Exception("错错错错错错错");
// }
int i = new Random().nextInt(2);
System.out.println("随机数为====================" + i);
System.out.println(2/i);
return 200;
}
}
记得在启动类新增注解
@SpringBootApplication
@EnableRetry
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application .class, args);
}
}
在没有用spring-retry之前写过基于函数式接口的重试
@FunctionalInterface
public interface Retry {
boolean action();
public static final int MAX_RETRY_COUNT_5 = 5;
public static final int INTERVAL_SECONDS_3 = 3;
public static void retry(int maxRetryCount, Retry workFunction,
Retry intervalFunctin) {
// 如果最大重试次数小于1,或重试工作函数为空,直接返回
if (maxRetryCount < 1 || null == workFunction) {
return;
}
// 执行最大重试次数次重试操作
for (int i = 0; i < maxRetryCount; i++) {
// 如果本次的执行结果为成功,则不再继续重试
if (workFunction.action()) {
return;
}
// 如果本次的执行结果为失败,则执行重试间隔函数之后继续重试执行工作函数
intervalFunctin.action();
}
System.out.println("have tried maxRetryCount!");
}
public static boolean doSleep(int seconds) {
try {
TimeUnit.SECONDS.sleep(seconds);
return true;
} catch (InterruptedException e) {
System.out.println("exception occurs when doSleep, e = " + e);
return false;
}
}
}
public class Test {
public static void main(String[] args) {
// 工作函数入参
boolean param = true;
Retry.retry(Retry.MAX_RETRY_COUNT_5, () -> doWork(param), () -> Retry.doSleep(Retry.INTERVAL_SECONDS_3));
}
public static boolean doWork(boolean param) {
System.out.println("start to do some work...");
// 为简单期间,将入参param的值取反,模拟工作函数的执行结果
boolean result = !param;
if (result) {
System.out.println("doWork success!");
} else {
System.out.println("doWork failed!");
}
return result;
}
}


