Spring实现了一套重试机制,功能简单实用。Spring Retry是从Spring Batch独立出来的一个功能,已经广泛应用于Spring Batch,Spring Integration, Spring for Apache Hadoop等Spring项目。
本文将讲述如何使用Spring Retry及其实现原理。
背景
重试,其实我们其实很多时候都需要的,为了保证容错性,可用性,一致性等。一般用来应对外部系统的一些不可预料的返回、异常等,特别是网络延迟,中断等情况。还有在现在流行的微服务治理框架中,通常都有自己的重试与超时配置,比如dubbo可以设置retries=1,timeout=500调用失败只重试1次,超过500ms调用仍未返回则调用失败。
如果我们要做重试,要为特定的某个操作做重试功能,则要硬编码,大概逻辑基本都是写个循环,根据返回或异常,计数失败次数,然后设定退出条件。这样做,且不说每个操作都要写这种类似的代码,而且重试逻辑和业务逻辑混在一起,给维护和扩展带来了麻烦。
从面向对象的角度来看,我们应该把重试的代码独立出来。
使用介绍
基本使用
先举个例子:
- @Configuration
- @EnableRetry
- public class Application {
- @Bean
- public RetryService retryService(){
- return new RetryService();
- }
- public static void main(String[] args) throws Exception{
- ApplicationContext applicationContext = new AnnotationConfigApplicationContext("springretry");
- RetryService service1 = applicationContext.getBean("service", RetryService.class);
- service1.service();
- }
- }
- @Service("service")
- public class RetryService {
- @Retryable(value = IllegalAccessException.class, maxAttempts = 5,
- backoff= @Backoff(value = 1500, maxDelay = 100000, multiplier = 1.2))
- public void service() throws IllegalAccessException {
- System.out.println("service method…");
- throw new IllegalAccessException("manual exception");
- }
- @Recover
- public void recover(IllegalAccessException e){
- System.out.println("service retry after Recover => " + e.getMessage());
- }
- }
@EnableRetry – 表示开启重试机制
@Retryable – 表示这个方法需要重试,它有很丰富的参数,可以满足你对重试的需求
@Backoff – 表示重试中的退避策略
@Recover – 兜底方法,即多次重试后还是失败就会执行这个方法
Spring-Retry 的功能丰富在于其重试策略和退避策略,还有兜底,监听器等操作。
然后每个注解里面的参数,都是很简单的,大家看一下就知道是什么意思,怎么用了,我就不多讲了。关注公众号Java技术栈,在后台回复:spring,可以获取我整理的 Spring 系列教程,非常齐全。