引用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) 参数含义:
标签:info,retry,RuntimeException,spring,重试,Retry,context,retryCount From: https://www.cnblogs.com/lxn0216/p/17934925.html