最近有一個業務需要有重試機制,感覺應該寫一個能夠重試的組件。
首先創建一個註解
/**
* @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(){
注意事項,如果用到事務,一定要讓攔截器高於事務執行。
至此就結束了。