try-catch-redo简单重试模式
public void commonRetry(Map<String, Object> dataMap) throws InterruptedException {
Map<String, Object> paramMap = Maps.newHashMap();
paramMap.put("tableName", "creativeTable");
paramMap.put("ds", "20160220");
paramMap.put("dataMap", dataMap);
boolean result = false;
try {
result = uploadToOdps(paramMap);
if (!result) {
Thread.sleep(1000);
uploadToOdps(paramMap); //一次重试
}
} catch (Exception e) {
Thread.sleep(1000);
uploadToOdps(paramMap);//一次重试
}
}
一般做处理尝试重连
while(someCondition()) {
try{
doSth();
break;
} catch(Throwable th) {
modifyCondition();
wait();
}
}
if(stillFail) {
doSthWhenStillFail();
}
可以有如下操作
1,记录 log
2,保存至Kafka,Redis,Mysql
3,尝试重新保存3次左右
public static void main(String[] args) {
RetryTemplate retryTemplate = new RetryTemplate();
SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
retryTemplate.setRetryPolicy(simpleRetryPolicy);
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(100);
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
RetryCallback<Object, Exception> retryCallback = new RetryCallback<Object, Exception>() {
@Override
public Object doWithRetry(RetryContext context) throws Exception {
System.out.println("do some thing..context.getRetryCount():" + context.getRetryCount());
Exception exception = new UserFamilyAccountLogServiceImpl().reUpload(context.getRetryCount());
if(exception == null){
return null;
}
throw exception;
}
};
RecoveryCallback<Object> recoveryCallback = new RecoveryCallback<Object>() {
@Override
public Object recover(RetryContext context) throws Exception {
System.out.println("退出恢复操作实例");
return "null";
}
};
try {
retryTemplate.execute(retryCallback, recoveryCallback);
} catch (Exception e) {
e.printStackTrace();
}
}
private Exception reUpload(int retryCount){
if(retryCount == 1){
return new RuntimeException("重试异常");
}
return null;
}
4,重试之后再次判断操作 -- 一般用于连接池
参考博客
https://juejin.cn/post/6844903618148040712#heading-2