<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency>这里我们还引入了 aop 的依赖,因为 spring-retry 的原理就是基于 aop 来实现的
@EnableRetry @SpringBootApplication public class AsurplusApplication { public static void main(String[] args) { SpringApplication.run(AsurplusApplication.class, args); } }三、@Retryable
@Component public class TestRetry { int a = 0; @Retryable(value = {RuntimeException.class}, maxAttempts = 5, backoff = @Backoff(delay = 1000, multiplier = 2)) public String test() { a++; System.out.println(a + " - " + System.currentTimeMillis()); if (a < 10) { throw new RuntimeException("未满足条件"); } return "执行成功"; } }@Retryable 注解
random,随机指定延迟时间
@Recover public String recoverTest(RuntimeException e) { return "回调方法-" + e.getMessage(); }.方法的返回值必须与 @Retryable 方法一致
@Component public class TestRetry { // 堆代码 duidaima.com int a = 0; @Retryable(recover = "recoverTest1", value = {RuntimeException.class}, maxAttempts = 5, backoff = @Backoff(delay = 1000, multiplier = 2)) public String test() { a++; System.out.println(a + " - " + System.currentTimeMillis()); if (a < 10) { throw new RuntimeException("未满足条件"); } return "执行成功"; } @Recover public String recoverTest(RuntimeException e) { return "回调方法-" + e.getMessage(); } @Recover public String recoverTest1(RuntimeException e) { return "回调方法1-" + e.getMessage(); } }指定了回调方法为 recoverTest1