Spring AOP实现接口调用异常时重试

调用某个接口时,可能因为数据同步延迟等原因导致抛异常,很希望程序可以重试指定次数后再结束运行。

注意:接口需配合事务,当抛异常时,进行回滚,以撤销异常之前对数据库的操作。

@Aspect
@Component
public class AspectTryCount implements Ordered {
    private static final int DEFAULT_MAX_RETRIES = 2;

    private int maxRetries = DEFAULT_MAX_RETRIES;
    private int order = 1;

    @Pointcut("execution(* com.example.springdemo.service.*.*(..))")
    public void cut() {
    }

    @Override
    public int getOrder() {
        return this.order;
    }

    public int getMaxRetries() {
        return maxRetries;
    }

    public void setMaxRetries(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    @Around("cut()")
    public void tryCount(ProceedingJoinPoint joinPoint) throws Throwable {
        int numAttempts = 0;
        JdcException jdcException = null;
        boolean isDone = false;
        do {
            isDone = false;
            numAttempts++;
            try {
                joinPoint.proceed();
                isDone = true;
            } catch (JdcException exception) {
                jdcException = exception;
                System.out.println(numAttempts + " attempt...");
            }
        } while (numAttempts < maxRetries && !isDone);
        if (!isDone) {
            System.out.println("attempt 2 times but not work!");
            throw jdcException;
        }

    }

}

tips:需向ioc容器中注入bean:TransactionManager,需在配置类中开启事务:@EnableTransactionManagement,需再接口方法上添加事务注解:@Transactional

原文地址:https://www.cnblogs.com/kongieg/p/13605678.html