Spring retry 和 guava retryer重试、@async 异步执行注解
spring retry
-
依赖
<!-- spring-retry --> <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.46</version> </dependency> <!-- /spring-retry -->
-
代码实现
-
异常类
package com.retry.demo.springretry.exception; import lombok.Builder; import lombok.Getter; @Builder @Getter public class RetryException extends RuntimeException { private String code; private String message; }
-
主类
package net.fanci.stars; import net.fanci.stars.listener.PropertiesListener; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.retry.annotation.EnableRetry; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; @SpringBootApplication @EnableRetry public class StarsParentApplication { public static void main(String[] args) { // SpringApplication.run(StarsParentApplication.class, args); SpringApplication application = new SpringApplication(StarsParentApplication.class); //加载配置文件 application.addListeners(new PropertiesListener("config.properties")); application.run(args); } @Bean(name = "threadPoolTaskExecutor") public Executor threadPoolTaskExecutor() { return new ThreadPoolTaskExecutor(); } }
-
重试类
package com.retry.demo.springretry.serivce; import com.retry.demo.springretry.exception.RetryException; import lombok.extern.slf4j.Slf4j; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Recover; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Service; @Service @Slf4j public class RetryServiceImpl implements RetryService { int i = 1; // 需要指定 maxDelay @Override @Retryable(include = { RetryException.class}, maxAttempts = 4, backoff = @Backoff(delay = 3000l,maxDelay = 60 * 1000L, multiplier = 1)) public String retry() { log.info("测试retry"); //生产环境此处应该为调用第三方接口,判断接口返回code if (i == 3) { return i++ + ""; } i++; log.info("============" + i); RetryException retryException = RetryException.builder().code("9999").message("连接超时").build(); throw retryException; } @Recover public String recover(RetryException e) { log.info(e.getMessage()); return "6"; } }
-
guava retryer
-
依赖
<!-- guava-retrying --> <dependency> <groupId>com.github.rholder</groupId> <artifactId>guava-retrying</artifactId> <version>2.0.0</version> </dependency> <!-- /guava-retrying -->
-
实现类
package com.retry.demo.guavaretrying; import com.github.rholder