首先pom.xml增加如下依赖:
org.springframework.retry spring-retry1.2.2.RELEASE
工具类名称为RetryUtil,代码如下:
import org.springframework.retry.RetryPolicy;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.CompositeRetryPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.policy.TimeoutRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import java.util.HashMap;
import java.util.Map;
public class RetryUtil {
public static class Policy{
//单一策略
final public static int simple = 0;
//悲观策略
final public static int comp_single = 1;
//乐观策略
final public static int comp_muti = 2;
}
private int retryPolicy = 0;
private long fixedPeriodTime = 1000L;
private int maxRetryTimes = 3;
private int timeoutRetryPolicy = 5000;
private Map, Boolean> exceptionMap = new HashMap<>();
public RetryUtil() {}
public RetryUtil setRetryPolicy(int policy) {
retryPolicy = policy;
return this;
}
public RetryUtil setFixedPeriodTime(int time) {
fixedPeriodTime = time;
return this;
}
public RetryUtil setMaxRetryTimes(int times) {
maxRetryTimes = times;
return this;
}
public RetryUtil setTimeoutRetryPolicy(int time) {
timeoutRetryPolicy = time;
return this;
}
public RetryUtil addExceptionMap(Class c) {
exceptionMap.put(c, true);
return this;
}
public static RetryUtil instance() {
RetryUtil r = new RetryUtil();
return r;
}
public RetryTemplate build() {
RetryPolicy p = null;
switch (retryPolicy){
case Policy.simple:
p = new SimpleRetryPolicy(maxRetryTimes, exceptionMap);
break;
case Policy.comp_single:
case Policy.comp_muti:
// 重试次数
SimpleRetryPolicy simple = new SimpleRetryPolicy(maxRetryTimes, exceptionMap);
// 超时重试
TimeoutRetryPolicy policyTimeout = new TimeoutRetryPolicy();
policyTimeout.setTimeout(timeoutRetryPolicy);
RetryPolicy[] polices = {simple, policyTimeout};
boolean opt = retryPolicy == Policy.comp_single?false:true;
//策略组合
CompositeRetryPolicy comp = new CompositeRetryPolicy();
comp.setPolicies(polices);
comp.setOptimistic(opt);
p = comp;
break;
default:
p = new SimpleRetryPolicy(maxRetryTimes, exceptionMap);
break;
}
// 设置重试回退操作策略,主要设置重试间隔时间
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(fixedPeriodTime);
// 构建重试模板实例
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(p);
retryTemplate.setBackOffPolicy(backOffPolicy);
return retryTemplate;
}
}
使用如下:
RetryTemplate retry = RetryUtil.instance()
.setFixedPeriodTime(1000)
.setMaxRetryTimes(3)
.setTimeoutRetryPolicy(25000)
.addExceptionMap(HBaseConfNotExistException.class)
.setRetryPolicy(RetryUtil.Policy.comp_muti)
.build();
retry.execute(
//RetryCallback
retryContext -> {
needretryFunc();
return true;
},
retryContext -> {
//RecoveryCallback
log.info("重试失败");
return false;
}
);



