springBoot, Retry的使用
SpringBoot提供了Retry机制, 以应对内部发出请求 得不到响应, 而导致程序执行失败的问题
基本逻辑是 ( 以 "捕捉到异常"为条件触发 - - 重试 -- 最终补偿策略 )
##导入依赖
<!--Spring重试模块--> <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> </dependency>
这里写的示例, 以数字对比作为触发RuntimeException 为示例
import cn.hutool.core.util.RandomUtil; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Recover; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Service; @Service public class RetryService { /*
* @Recover的 第一个参数 必须是Throwable ,最好与@Retryable方法 捕捉的异常相同 * 返回值,必须与@Retryable方法相同,否则不执行 * * */ @Retryable(value = RuntimeException.class, //捕捉的异常 maxAttempts = 3, //最大重试次数 backoff = @Backoff(multiplier = 2,delay = 2000L)) //重试策略 public int retry(int num){ int i = RandomUtil.randomInt(20, 100); if (i<num){ //触发异常 System.out.println("数字 =" + i+"比 "+ num +"小 ,,将重试"); throw new RuntimeException(); } return num; } @Recover //全部失败后 public int recover(Exception e){ System.out.println("全部重试结束,以recover补偿"); return 88; } }
## 测试用例
@SpringBootTest @RunWith(SpringRunner.class) public class TestRetry { @Autowired RetryService retryService; @Test public void retryTeest(){ int recover = retryService.retry(66); System.out.println("recover = " + recover); } }
累累的 回复

浙公网安备 33010602011771号
漏了很关键的@EnableRetry注解,放到RetryService或者SpringBootApplication上都行