spring-retry 重试机制

引用pom.xml

 <dependency>
    <groupId>org.springframework.retry</groupId>
     <artifactId>spring-retry</artifactId>
    <version>1.3.4</version>
</dependency>

注:本人测试使用jdk8

例子:

复制代码
public void demo(String str) throws Throwable {

        RetryTemplate build = RetryTemplate.builder().maxAttempts(10)//最大重试次数
                .exponentialBackoff(1000, 2, 3 * 1000)
                .retryOn(RuntimeException.class)//遇到RuntimeException触发重试
                .build();
        build.execute((RetryCallback<Object, Throwable>) context -> {
            //执行业务逻辑
            int retryCount = context.getRetryCount()+1;
            log.info(">>" + str + " Retry 触发时间:" + DateUtils.emptyFormat(new Date()) + ",触发次数:" + retryCount);
            //if (retryCount < 3) {
                log.info(">> Retry 抛出一下 RuntimeException");
                throw new RuntimeException("RuntimeException");
            //}
            //log.info(">> Retry 执行完毕");
            //return true;
        }, (RecoveryCallback<Object>) context -> {
            //当重试次数耗尽时 重试次数耗尽时触发,降级业务逻辑
            int retryCount = context.getRetryCount();
            log.info("Retry 重试次数耗尽时触发,降级业务逻辑.共重试次数" + retryCount);


            return null;
        });

    }public void demo(String str) throws Throwable {

        RetryTemplate build = RetryTemplate.builder().maxAttempts(10)//最大重试次数
                .exponentialBackoff(1000, 2, 3 * 1000)
                .retryOn(RuntimeException.class)//遇到RuntimeException触发重试
                .build();
        build.execute((RetryCallback<Object, Throwable>) context -> {
            //执行业务逻辑
            int retryCount = context.getRetryCount()+1;
            log.info(">>" + str + " Retry 触发时间:" + DateUtils.emptyFormat(new Date()) + ",触发次数:" + retryCount);
            //if (retryCount < 3) {
                log.info(">> Retry 抛出一下 RuntimeException");
                throw new RuntimeException("RuntimeException");
            //}
            //log.info(">> Retry 执行完毕");
            //return true;
        }, (RecoveryCallback<Object>) context -> {
            //当重试次数耗尽时 重试次数耗尽时触发,降级业务逻辑
            int retryCount = context.getRetryCount();
            log.info("Retry 重试次数耗尽时触发,降级业务逻辑.共重试次数" + retryCount);


            return null;
        });

    }
复制代码

 

执行结果:

 

参考文档:
https://github.com/spring-projects/spring-retry
exponentialBackoff(1000, 2, 3 * 1000) 参数含义:

 

posted @   爱,诗意永存  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
历史上的今天:
2020-12-29 spring_cloud组件之Feign
点击右上角即可分享
微信分享提示