01 Spring Retry

Wu Jun 2020-01-14 12:12:14
06 Spring > 10 Retry

spring-retry 项目地址:https://github.com/spring-projects/spring-retry

1 注解介绍

2 引入 Spring Retry 依赖

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>${version}</version>
</dependency>

额外依赖 AOP

Spring Boot 项目,推荐依赖 Spring Boot starter for AOP

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <version>${version}</version>
</dependency>

非 Spring Boot 项目,依赖 AspectJ 的 aspectjweaver

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>${version}</version>
</dependency>

3 在启动入口加入重试配置

添加 @EnableRetry 注解

@SpringBootApplication
@EnableRetry
public class RetryApplication {
	public static void main(String[] args) throws Exception{
		SpringApplication.run(RetryApplication.class, args);
	}
}

4 编写测试 service

@Service
public class RetryService {
    @Retryable(value= {RemoteAccessException.class},maxAttempts = 5,backoff = @Backoff(delay = 5000l,multiplier = 1))
    public void retryTest() throws Exception {
        System.out.println("do something...");
        throw new RemoteAccessException("RemoteAccessException....");
    }
    @Recover
    public void recover(RemoteAccessException e) {
        System.out.println(e.getMessage());
        System.out.println("recover....");
    }
}

5 测试 service

@Configuration
@EnableRetry
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class RetryServiceMain {
    @Bean
    public RetryService retryService(){
        return new RetryService();
    }
    public static void main(String[] args) throws Exception{
        final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(RetryServiceMain.class);
        final RetryService retryService = applicationContext.getBean(RetryService.class);
        retryService.retryTest();
    }
}