2019独角兽企业重金招聘Python工程师标准>>>
1、定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface RetryMethod {int retryCnt() default 1;int retryUnit() default 1000;}
2、切面
@Aspect
@Component
@Log4j
public class AopIntercepter {private Logger logger = LoggerFactory.getLogger(this.getClass());@Around("@annotation(com.youzan.test.util.aop.RetryMethod)")public void around(ProceedingJoinPoint joinPoint) throws Throwable{Method currentMethod = this.getCurrentMethod(joinPoint);String mName = currentMethod.getName();Object result = null;RetryMethod retry = currentMethod.getAnnotation(RetryMethod.class);boolean flag = false;int retryCount = retry.retryCnt();while (!flag&&retryCount>0){flag = true;try {logger.info("方法名: "+mName+"开始执行");System.out.println("方法名: "+mName+"开始执行");result = joinPoint.proceed();}catch (Throwable e){flag = false;retryCount -- ;Thread.sleep(retry.retryUnit());logger.info("方法名: "+mName+"重试第"+(retry.retryCnt()-retryCount)+"次");if(retryCount == 0){throw e;}}}}private Method getCurrentMethod(ProceedingJoinPoint joinPoint) {MethodSignature msig = (MethodSignature)joinPoint.getSignature();try {return joinPoint.getTarget().getClass().getMethod(msig.getName(), msig.getParameterTypes());} catch (NoSuchMethodException var4) {throw new RuntimeException("这就不该有问题");}}}
3、使用
@Component
public class AopTestCase {private int i &#61; 0;&#64;RetryMethod(retryCnt&#61;2,retryUnit &#61; 1050)public void test(){Long sum &#61; 5l;System.out.println("hello,i&#61;"&#43;i);i&#43;&#43;;Assert.assertTrue(sum<0,"大于0");System.out.println("after test");}public void testMethod(){System.out.println("test test");}
}