如何使用 AspectJ 在 java 中实现重试机制

How to implement Retry mechanism in java using AspectJ

我正在尝试使用 AspectJ 实现重试机制。如果一个方法抛出任何异常 AspectJ 应该再次调用方法。

这是我的代码:

重试注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Retry {
    int retryCount();
}

重试方面:

@Aspect
public class RetryAspect {
    @Around("@annotation(main.Retry)")
    public Object profile(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object response = null;
        Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
        Retry annotation = method.getAnnotation(Retry.class);
        int retryCount = annotation.retryCount();
        boolean successfull = false;
        do{
            try {
                response = proceedingJoinPoint.proceed();
                successfull = true;
            }catch(Exception ex){
                retryCount--;
                if(retryCount < 0){
                    throw ex;
                }
            }
        }while(!successfull);
        return response;
    }
}

主要方法:

public class Main {

    @Retry(retryCount = 1)
    public int method1() throws Exception  {
        System.out.println("method 1");
        throw new Exception();
    }

    public static void main(String[] args) throws Exception {
        Main m = new Main();
        boolean successfull = false;
        m.method1();
        System.out.println("Exit main");
    }
}

如果我的理解是正确的程序应该打印 "method 1" 两次并抛出 exception.But "method 1" 被打印 4 次。 这是输出:

method 1
method 1
method 1
method 1
Exception in thread "main" java.lang.Exception
    at main.Main.method1_aroundBody0(Main.java:8)
    at main.Main.method1_aroundBody1$advice(Main.java:24)
    at main.Main.method1(Main.java:1)
    at main.Main.method1_aroundBody2(Main.java:14)
    at main.Main.method1_aroundBody3$advice(Main.java:24)
    at main.Main.main(Main.java:14)

如果我的实现有任何错误,请指出。

您使用的是 AspectJ,而不是 Spring AOP,这就是您的切入点与两者都匹配的原因

  • call()(方法调用的来源)和
  • execution()(目标方法本身)

joinpoints,因此您看到 4 个而不是 2 个日志输出。如果您养成在建议开始时打印完整连接点(而不仅仅是签名或连接点的另一小部分)的习惯,至少在开发过程中,您自己很容易发现。您可以稍后将其注释掉。所以你可以添加

System.out.println(proceedingJoinPoint);

你会明白我的意思的。

解决该问题的最简单方法是将切入点限制为调用或执行。如果您可以选择,我建议使用后者,因为最好只编写一个方法而不是 100 个调用方。你要修改你的切入点为(未经测试,我在路上写"hands-free")

@Around("@annotation(main.Retry) && execution(* *(..))")