Springboot整合spring retry重试机制
1.导入springboot坐标
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>
</parent>
2.除必要坐标外,加入spring retry坐标
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
3.spring retry通用方法
package com.mytest.utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
@Component
public class SpringRetryUtils {
@Autowired
private InnerRetryInvoker innerRetryInvoker;
public Object excute(Object targetObject,String methodName,Object... args){
Method method = BeanUtils.findMethodWithMinimalParameters(targetObject.getClass(), methodName);
Class<?> returnType = method.getReturnType();
Object returnObj = null;
try {
returnObj = innerRetryInvoker.invoke(targetObject,method,returnType,args);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return returnObj;
}
@Component
public class InnerRetryInvoker{
public InnerRetryInvoker() {
}
@Retryable(backoff=@Backoff(delay=300L,multiplier=1),label=“重试查询”)
Object invoke(Object targetObject, Method method,Class<?> returnType,Object... args) throws InvocationTargetException, IllegalAccessException {
Object invoke = method.invoke(targetObject, args);
if(Map.class.isAssignableFrom(returnType)){
if(CollectionUtils.isEmpty((Map<?, ?>) invoke)){
throw new RuntimeException("查询结果集为空!");
}
}else if(List.class.isAssignableFrom(returnType)){
if(CollectionUtils.isEmpty((Map<?, ?>) invoke)){
throw new RuntimeException("查询结果集为空!");
}
}
return invoke;
}
}
}
OK,搞定了!!!