最近有一个业务需要有重试机制,感觉应该写一个能够重试的组件。
首先创建一个注解
/**
* @Author GUOSHAOHUA093
* @Description 重试拦截
* @Date 9:14 2018/12/8
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface IsTryAgain {
int times() default 1;
Class<? extends Exception> exception() default Exception.class;
}
在常见一个切入点
/**
*@Author GUOSHAOHUA093
*@Description 重试切点
*@Date 14:07 2018/12/8
*/
@Component //声明组件
@Aspect
public class TryAgainPointcut {
@Pointcut("execution(* com.pingan.medical.service..*(..))")
public void businessService() {
}
}
因为我们希望每次重试都是一个新的事务,所以我们需要高于事务去执行,并且我们项根据传入的Exception自行来判断对什么样的异常进行重试(目前只支持放入一种哈,后续看心情开发中。。。。)。
/**
*@Author GUOSHAOHUA093
*@Description 重试拦截处理方法
*@Date 14:09 2018/12/8
*/
@Component //声明组件
@Aspect
class RetryAgainExecutor implements Ordered {
private static final Logger logger = LoggerFactory.getLogger(RetryAgainExecutor.class);
private static final int DEFAULT_MAX_RETRIES = 2;
private int maxRetries = DEFAULT_MAX_RETRIES;
private int order = 2;
public void setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
}
public int getOrder() {
return this.order;
}
@Around("@annotation(com.pingan.medical.config.interceptor.tryAgain.IsTryAgain)")
public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
//得到重试次数
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
IsTryAgain isTryAgain = method.getAnnotation(IsTryAgain.class);
int maxTimes = isTryAgain.times();
int numAttempts = 0;
Exception retryException;
do {
numAttempts++;
try {
logger.info("这是第"+numAttempts+"次访问");
return pjp.proceed();
}catch(Exception ex) {
if (isTryAgain.exception().isInstance(Object.class) || isTryAgain.exception().isInstance(ex)) {
retryException = ex;
} else {
throw ex;
}
}
}while(numAttempts < maxTimes);
throw retryException;
}
}
用的时候就很方便啦,写了exception就会对指定的exception做拦截,不写就会对所有的exception进行拦截。
@IsTryAgain(times = 2,exception = CustomException.class)
@Transactional
public ApiResult test() throw CustomException(){
注意事项,如果用到事务,一定要让拦截器高于事务执行。
至此就结束了。