• Spring的重试机制-SpringRetry


    在我们的日常开发中,经查会遇到调用接口失败的情况,这时候就需要通过一些方法来进行重试,比如通过while循环手动重复调用或,或者通过记录错误接口url和参数到数据库,然后手动调用接口,或者通过JDK/CGLib动态代理的方式来进行重试,但是这种方法比较笨重,且对原有逻辑代码的入侵性比较大。

    SpringRetry却可以通过注解,在不入侵原有业务逻辑代码的方式下,优雅的实现重处理功能。

    1:添加pom依赖

     <dependency>
        <groupId>org.springframework.retry</groupId>
        <artifactId>spring-retry</artifactId>
     </dependency>
    
    • 1
    • 2
    • 3
    • 4

    2:主启动类开启@EnableRetry注解

    /**
     * 主启动类
     * EnableCaching允许使用注解进行缓存
     * 添加注解@EnableRetry
     * 
     * @author hua
     */
    @EnableRetry
    @EnableCaching
    @SpringBootApplication
    @MapperScan(basePackages = "com.it.mapper")
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    3:在重试所调用方法上添加@Retryable注解

    @Service
    @Slf4j
    public class SpringRetryService {
        /**
         * 重试所调用方法
         *
         * delay=2000L表示延迟2秒 multiplier=2表示两倍 即第一次重试2秒后,第二次重试4秒后,第三次重试8秒后
         * @return
         */
        @Retryable(value = {RemoteAccessException.class}, maxAttempts = 3, backoff = @Backoff(delay = 2000L, multiplier = 2))
        public boolean call(Integer param) {
            return retryMethod(param);
        }
    
        /**
         * 超过最大重试次数或抛出没有指定重试的异常
         * @param e
         * @param param
         * @return
         */
        @Recover
        public boolean recover(Exception e, Integer param) {
            log.info("请求参数为: ", param);
            log.info("超过最大重试次数或抛出没有指定重试的异常, e = {} ", e.getMessage());
            return false;
        }
    
        public static boolean retryMethod(Integer param) {
            int i = new Random().nextInt(param);
            log.info("随机生成的数:{}", i);
    
            if (1 == i) {
                log.info("为1,返回true.");
                return true;
            } else if (i < 1) {
                log.info("小于1,抛出参数异常.");
                throw new IllegalArgumentException("参数异常");
            } else if (i > 1 && i < 10) {
                log.info("大于1,小于10,抛出参数异常.");
                return false;
            } else {
                //为其他
                log.info("大于10,抛出自定义异常.");
                throw new RemoteAccessException("大于10,抛出自定义异常");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    Spring Retry 注解属性详解
    1、@EnableRetry
    作用于SpringbootApplication启动类,开启spring retry。
    proxyTargetClass:默认值为false,设置为true时为CGLIB代理。
    2、@Retryable 作用于需要进行重试的方法
    value:指定处理的异常类,默认为空
    include:指定处理的异常类,默认为空,当include和exclude为空时,默认所有异常
    exclude:指定哪些异常不处理,默认空
    maxAttempts:最大重试次数。默认3次
    backoff: 重试补偿策略。默认使用@Backoff注解
    3、@Backoff 作用于backoff中的补偿策略
    delay:指定等待时间,没有设置的话默认为1000ms
    maxDelay:最大重试时间,没有设置默认为3000ms
    multiplier:下一次调用时间的乘数
    random:随机等待时间,默认值为false
    4、@Recover
    用于对retry方法的异常抛出的特殊处理,可做熔断、降级、日志等操作。入参必须和retry对应方法所抛出的异常类型相同。

    4:单元测试

    @SpringBootTest
    @Slf4j
    public class SpringRetryServiceTest {
        @Autowired
        private SpringRetryService springRetryService;
    
        @Test
        void contextLoads() {
            boolean result = springRetryService.call(100);
            log.info("方法返回结果为: {}", result);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    5:测试结果

    在这里插入图片描述

    6:源码下载

    下载地址 springboot-cacheable 欢迎star哦~
    在这里插入图片描述

    参考资料
    @Retryable注解,优雅的实现循环重试功能
    SpringRetry(spring的重试机制)——只需一个注解
    Spring 中的重试机制,简单、实用!

  • 相关阅读:
    目标检测新SOTA:YOLOv9问世,新架构让传统卷积重焕生机(附代码)
    JavaScript深拷贝
    C++运算符重载+,*在QT中的实现演示
    微信小程序 prettier 格式化
    mmap在嵌入式中的应用
    详解机器视觉性能指标相关概念——混淆矩阵、IoU、ROC曲线、mAP等
    <数据集>钢索缺陷检测数据集<目标检测>
    使用ansible-app2k8s管理和部署服务到 kubernetes
    ObjectiveC-08-OOP面向对象程序设计-类的分离与组合
    DNS域名解析服务
  • 原文地址:https://blog.csdn.net/jike11231/article/details/132645737