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) 参数含义:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
2020-12-29 spring_cloud组件之Feign