1、java重试两种实现方式
1.1 模板方法
定义模板类
RetryTemplate
package com.mine.template;
public abstract class RetryTemplate {
// 重试次数
private int retryTime = 5;
// 重试的睡眠时间
private int sleepTime = 3000;
public void setSleepTime(int sleepTime) {
this.sleepTime = sleepTime;
}
public void setRetryTime(int retryTime) {
this.retryTime = retryTime;
}
protected abstract void doAction() throws Exception;
public void execute() throws Exception {
for (int i = 0; i < retryTime; i++) {
try {
doAction();
return;
} catch (Exception e) {
Thread.sleep(sleepTime);
}
}
}
}
测试类
TestRetryTemplate
package com.mine.template;
public class TestRetryTemplate extends RetryTemplate {
private int i = 1;
@Override
protected void doAction() throws Exception {
System.out.println("----------------");
System.out.println(System.currentTimeMillis());
if (i++ >= 3) {
System.out.println("sucess");
} else {
System.out.println("failure");
throw new Exception();
}
}
public static void main