zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    一些简单的问题
    WebRTC的 windows 7 环境搭建
    HTML常用标签
    参考C#编程规范
    C#窗体调用(转载)
    java中的小知识(不断更行中。。。。。)
    CF1483E Vabank 题解
    CF755G PolandBall and Many Other Balls 题解
    CF1483D Useful Edges 题解
    CF1368F Lamps on a Circle 题解
  • 原文地址:https://www.cnblogs.com/kongieg/p/13605678.html
Copyright © 2011-2022 走看看