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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM