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

  • 相关阅读:
    JavaSE—集合框架
    JavaSE——集合框架
    RocketMq 在Netty 下是如何进行消息封装传输
    SpringBoot 初始化流程以及各种常见第三方配置的源码实现
    Java 重要知识点,踩过的坑
    Mysql 知识储备以及InnoDB
    java 编程英语单词,语句
    PlantUML
    Rocketmq broker 消息仓库
    AutowiredAnnotationBeanPostProcessor 的一些思考
  • 原文地址:https://www.cnblogs.com/kongieg/p/13605678.html
Copyright © 2011-2022 走看看