强悍的Spring之Spring Retry
在日常开发中,我们经常会遇到需要调用外部服务和接口的场景。外部服务对于调用者来说一般都是不可靠的,尤其是在网络环境比较差的情况下,网络抖动很容易导致请求超时等异常情况,这时候就需要使用失败重试策略重新调用 API 接口来获取。重试策略在服务治理方面也有很广泛的使用,通过定时检测,来查看服务是否存活。
Spring异常重试框架Spring Retry
Spring Retry支持集成到Spring或者Spring Boot项目中,而它支持AOP的切面注入写法,所以在引入时必须引入aspectjweaver.jar包。
1.引入maven依赖
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.6</version>
</dependency>
2.添加@Retryable和@Recover注解
@Retryable注解,被注解的方法发生异常时会重试
- value:指定发生的异常进行重试
- include:和value一样,默认空,当exclude也为空时,所有异常都重试
- exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试
- maxAttemps:重试次数,默认3
- backoff:重试补偿机制,默认没有
@Backoff注解
- delay:指定延迟后重试
- multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒
@Recover注解:
当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调。
@Service
public class RemoteService {
@Retryable(value = {Exception.class}, maxAttempts = 5, backoff = @Backoff(delay = 5000L, multiplier = 1))
public void call() {
System.out.println(LocalDateTime.now() + ": do something...");
throw new RuntimeException(LocalDateTime.now() + ": 运行调用异常");
}
@Recover
public void recover(Exception e) {
System.out.println(e.getMessage());
}
3.启用重试功能
启动类上面添加@EnableRetry注解,启用重试功能,或者在使用retry的service上面添加也可以,或者Configuration配置类上面。
建议所有的Enable配置加在启动类上,可以清晰的统一管理使用的功能。
@SpringBootApplication
@EnableRetry
public class App {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
System.out.println("Start app success.");
RemoteService bean = context.getBean(RemoteService.class);
bean.call();
}
}
4.启动服务,运行测试
通过在启动类Context调用服务看到如下打印:
2019-03-09T15:22:12.781: do something...
2019-03-09T15:22:17.808: do something...
2019-03-09T15:22:22.835: do something...
2019-03-09T15:22:27.861: do something...
2019-03-09T15:22:32.887: do something...
2019-03-09T15:22:32.887: 运行调用异常
基于guava的重试组件Guava-Retryer
直接看组件作者对此组件的介绍:
This is a small extension to Google’s Guava library to allow for the creation of configurable retrying strategies for an arbitrary function call, such as something that talks to a remote service with flaky uptime.(这是对Google的guava库的一个小扩展,允许为任意函数调用创建可配置的重试策略,例如与运行时间不稳定的远程服务对话的策略。)
第一步引入maven坐标:
<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
</dependency>
1.其主要接口及策略介绍
- Attempt:一次执行任务;
- AttemptTimeLimiter:单次任务执行时间限制(如果单次任务执行超