Spring中的重试机制,简单、实用!

开发 后端
本文将讲述如何使用Spring Retry及其实现原理。一起来了解一下吧。

 概要

Spring实现了一套重试机制,功能简单实用。Spring Retry是从Spring Batch独立出来的一个功能,已经广泛应用于Spring Batch,Spring Integration, Spring for Apache Hadoop等Spring项目。

本文将讲述如何使用Spring Retry及其实现原理。

背景

重试,其实我们其实很多时候都需要的,为了保证容错性,可用性,一致性等。一般用来应对外部系统的一些不可预料的返回、异常等,特别是网络延迟,中断等情况。还有在现在流行的微服务治理框架中,通常都有自己的重试与超时配置,比如dubbo可以设置retries=1,timeout=500调用失败只重试1次,超过500ms调用仍未返回则调用失败。

如果我们要做重试,要为特定的某个操作做重试功能,则要硬编码,大概逻辑基本都是写个循环,根据返回或异常,计数失败次数,然后设定退出条件。这样做,且不说每个操作都要写这种类似的代码,而且重试逻辑和业务逻辑混在一起,给维护和扩展带来了麻烦。

从面向对象的角度来看,我们应该把重试的代码独立出来。

使用介绍

基本使用

先举个例子: 

  1. @Configuration  
  2. @EnableRetry  
  3. public class Application {  
  4.     @Bean  
  5.     public RetryService retryService(){  
  6.         return new RetryService();  
  7.     } 
  8.      public static void main(String[] args) throws Exception{  
  9.         ApplicationContext applicationContext = new AnnotationConfigApplicationContext("springretry");  
  10.         RetryService service1 = applicationContext.getBean("service", RetryService.class);  
  11.         service1.service();  
  12.     }  
  13.  
  14. @Service("service")  
  15. public class RetryService {  
  16.     @Retryable(value = IllegalAccessException.class, maxAttempts = 5 
  17.             backoff= @Backoff(value = 1500maxDelay = 100000multiplier = 1.2))  
  18.     public void service() throws IllegalAccessException {  
  19.         System.out.println("service method...");  
  20.         throw new IllegalAccessException("manual exception");  
  21.     }  
  22.     @Recover  
  23.     public void recover(IllegalAccessException e){  
  24.         System.out.println("service retry after Recover => " + e.getMessage());  
  25.     }  

@EnableRetry - 表示开启重试机制

@Retryable - 表示这个方法需要重试,它有很丰富的参数,可以满足你对重试的需求

@Backoff - 表示重试中的退避策略

@Recover - 兜底方法,即多次重试后还是失败就会执行这个方法

Spring-Retry 的功能丰富在于其重试策略和退避策略,还有兜底,监听器等操作。

然后每个注解里面的参数,都是很简单的,大家看一下就知道是什么意思,怎么用了,我就不多讲了。关注公众号Java技术栈,在后台回复:spring,可以获取我整理的 Spring 系列教程,非常齐全。

重试策略

看一下Spring Retry自带的一些重试策略,主要是用来判断当方法调用异常时是否需要重试。(下文原理部分会深入分析实现)

  •  SimpleRetryPolicy 默认最多重试3次
  •  TimeoutRetryPolicy 默认在1秒内失败都会重试
  •  ExpressionRetryPolicy 符合表达式就会重试
  •  CircuitBreakerRetryPolicy 增加了熔断的机制,如果不在熔断状态,则允许重试
  •  CompositeRetryPolicy 可以组合多个重试策略
  •  NeverRetryPolicy 从不重试(也是一种重试策略哈)
  •  AlwaysRetryPolicy 总是重试

….等等

退避策略

看一下退避策略,退避是指怎么去做下一次的重试,在这里其实就是等待多长时间。(下文原理部分会深入分析实现)

  •  FixedBackOffPolicy 默认固定延迟1秒后执行下一次重试
  •  ExponentialBackOffPolicy 指数递增延迟执行重试,默认初始0.1秒,系数是2,那么下次延迟0.2秒,再下次就是延迟0.4秒,如此类推,最大30秒。
  •  ExponentialRandomBackOffPolicy 在上面那个策略上增加随机性
  •  UniformRandomBackOffPolicy 这个跟上面的区别就是,上面的延迟会不停递增,这个只会在固定的区间随机
  •  StatelessBackOffPolicy 这个说明是无状态的,所谓无状态就是对上次的退避无感知,从它下面的子类也能看出来

原理

原理部分我想分开两部分来讲,一是重试机制的切入点,即它是如何使得你的代码实现重试功能的;二是重试机制的详细,包括重试的逻辑以及重试策略和退避策略的实现。另外,关注公众号Java技术栈,在后台回复:面试,可以获取我整理的 Spring 系列面试题和答案,非常齐全。

切入点

@EnableRetry 

  1. @Target(ElementType.TYPE)  
  2. @Retention(RetentionPolicy.RUNTIME)  
  3. @EnableAspectJAutoProxy(proxyTargetClass = false 
  4. @Import(RetryConfiguration.class)  
  5. @Documented  
  6. public @interface EnableRetry {  
  7.  /**  
  8.   * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed  
  9.   * to standard Java interface-based proxies. The default is {@code false}.  
  10.   *  
  11.   * @return whether to proxy or not to proxy the class  
  12.   */  
  13.  boolean proxyTargetClass() default false;  

我们可以看到@EnableAspectJAutoProxy(proxyTargetClass = false)这个并不陌生,就是打开Spring AOP功能。

重点看看@Import(RetryConfiguration.class)@Import相当于注册这个Bean

我们看看这个RetryConfiguration是个什么东西:

它是一个AbstractPointcutAdvisor,它有一个pointcut和一个advice。我们知道,在IOC过程中会根据PointcutAdvisor类来对Bean进行Pointcut的过滤,然后生成对应的AOP代理类,用advice来加强处理。

看看RetryConfiguration的初始化: 

  1. @PostConstruct  
  2. public void init() {  
  3.     Set<Class<? extends Annotation>> retryableAnnotationTypes = new LinkedHashSet<Class<? extends Annotation>>(1);  
  4.     retryableAnnotationTypes.add(Retryable.class);  
  5.     //创建pointcut  
  6.     this.pointcut = buildPointcut(retryableAnnotationTypes);  
  7.     //创建advice  
  8.     this.advice = buildAdvice();  
  9.     if (this.advice instanceof BeanFactoryAware) {  
  10.         ((BeanFactoryAware) this.advice).setBeanFactory(beanFactory);  
  11.     }  
  12.  
  1. protected Pointcut buildPointcut(Set<Class<? extends Annotation>> retryAnnotationTypes) {  
  2.     ComposablePointcut result = null 
  3.     for (Class<? extends Annotation> retryAnnotationType : retryAnnotationTypes) {  
  4.         Pointcut filter = new AnnotationClassOrMethodPointcut(retryAnnotationType);  
  5.         if (result == null) {  
  6.             result = new ComposablePointcut(filter);  
  7.         }  
  8.         else {  
  9.             result.union(filter);  
  10.         }  
  11.     }  
  12.     return result;  

上面代码用到了AnnotationClassOrMethodPointcut,其实它最终还是用到了AnnotationMethodMatcher来根据注解进行切入点的过滤。这里就是@Retryable注解了。 

  1. //创建advice对象,即拦截器  
  2. protected Advice buildAdvice() {  
  3.     //下面关注这个对象  
  4.  AnnotationAwareRetryOperationsInterceptor interceptor = new AnnotationAwareRetryOperationsInterceptor();  
  5.  if (retryContextCache != null) {  
  6.   interceptor.setRetryContextCache(retryContextCache);  
  7.  }  
  8.  if (retryListeners != null) {  
  9.   interceptor.setListeners(retryListeners);  
  10.  }  
  11.  if (methodArgumentsKeyGenerator != null) {  
  12.   interceptor.setKeyGenerator(methodArgumentsKeyGenerator);  
  13.  }  
  14.  if (newMethodArgumentsIdentifier != null) {  
  15.   interceptor.setNewItemIdentifier(newMethodArgumentsIdentifier);  
  16.  } 
  17.  if (sleeper != null) {  
  18.   interceptor.setSleeper(sleeper); 
  19.  }  
  20.  return interceptor;  

AnnotationAwareRetryOperationsInterceptor

继承关系

可以看出AnnotationAwareRetryOperationsInterceptor是一个MethodInterceptor,在创建AOP代理过程中如果目标方法符合pointcut的规则,它就会加到interceptor列表中,然后做增强,我们看看invoke方法做了什么增强。 

  1. @Override  
  2. public Object invoke(MethodInvocation invocation) throws Throwable {  
  3.     MethodInterceptor delegate = getDelegate(invocation.getThis(), invocation.getMethod());  
  4.     if (delegate != null) {  
  5.         return delegate.invoke(invocation);  
  6.     }  
  7.     else {  
  8.         return invocation.proceed();  
  9.     }  

这里用到了委托,主要是需要根据配置委托给具体“有状态”的interceptor还是“无状态”的interceptor。 

  1. private MethodInterceptor getDelegate(Object target, Method method) {  
  2.     if (!this.delegates.containsKey(target) || !this.delegates.get(target).containsKey(method)) {  
  3.         synchronized (this.delegates) {  
  4.             if (!this.delegates.containsKey(target)) { 
  5.                 this.delegates.put(target, new HashMap<Method, MethodInterceptor>());  
  6.             }  
  7.             Map<Method, MethodInterceptor> delegatesForTarget = this.delegates.get(target);  
  8.             if (!delegatesForTarget.containsKey(method)) {  
  9.                 Retryable retryable = AnnotationUtils.findAnnotation(method, Retryable.class);  
  10.                 if (retryable == null) {  
  11.                     retryable = AnnotationUtils.findAnnotation(method.getDeclaringClass(), Retryable.class);  
  12.                 }  
  13.                 if (retryable == null) {  
  14.                     retryable = findAnnotationOnTarget(target, method);  
  15.                 }  
  16.                 if (retryable == null) {  
  17.                     return delegatesForTarget.put(method, null);  
  18.                 }  
  19.                 MethodInterceptor delegate;  
  20.                 //支持自定义MethodInterceptor,而且优先级最高 
  21.  
  22.                 if (StringUtils.hasText(retryable.interceptor())) {  
  23.                     delegate = this.beanFactory.getBean(retryable.interceptor(), MethodInterceptor.class);  
  24.                 }  
  25.                 else if (retryable.stateful()) {  
  26.                     //得到“有状态”的interceptor  
  27.                     delegate = getStatefulInterceptor(target, method, retryable);  
  28.                 }  
  29.                 else {  
  30.                     //得到“无状态”的interceptor  
  31.                     delegate = getStatelessInterceptor(target, method, retryable);  
  32.                 }  
  33.                 delegatesForTarget.put(method, delegate);  
  34.             }  
  35.         }  
  36.     }  
  37.     return this.delegates.get(target).get(method);  

getStatefulInterceptor和getStatelessInterceptor都是差不多,我们先看看比较简单的getStatelessInterceptor。 

  1. private MethodInterceptor getStatelessInterceptor(Object target, Method method, Retryable retryable) {  
  2.     //生成一个RetryTemplate  
  3.     RetryTemplate template = createTemplate(retryable.listeners());  
  4.     //生成retryPolicy  
  5.     template.setRetryPolicy(getRetryPolicy(retryable));  
  6.     //生成backoffPolicy  
  7.     template.setBackOffPolicy(getBackoffPolicy(retryable.backoff()));  
  8.     return RetryInterceptorBuilder.stateless()  
  9.             .retryOperations(template)  
  10.             .label(retryable.label())  
  11.             .recoverer(getRecoverer(target, method))  
  12.             .build();  

具体生成retryPolicy和backoffPolicy的规则,我们等下再回头来看。

RetryInterceptorBuilder其实就是为了生成RetryOperationsInterceptor。RetryOperationsInterceptor也是一个MethodInterceptor,我们来看看它的invoke方法。

分享资料:Spring Boot 学习笔记太全了! 

  1. public Object invoke(final MethodInvocation invocation) throws Throwable {  
  2.     String name;  
  3.     if (StringUtils.hasText(label)) {  
  4.         name = label 
  5.     } else {  
  6.         name = invocation.getMethod().toGenericString();  
  7.     }  
  8.     final String label = name 
  9.     //定义了一个RetryCallback,其实看它的doWithRetry方法,调用了invocation的proceed()方法,是不是有点眼熟,这就是AOP的拦截链调用,如果没有拦截链,那就是对原来方法的调用。  
  10.     RetryCallback<Object, Throwable> retryCallback = new RetryCallback<Object, Throwable>() {  
  11.         public Object doWithRetry(RetryContext context) throws Exception {  
  12.             context.setAttribute(RetryContext.NAME, label);   
  13.             /*  
  14.              * If we don't copy the invocation carefully it won't keep a reference to  
  15.              * the other interceptors in the chain. We don't have a choice here but to  
  16.              * specialise to ReflectiveMethodInvocation (but how often would another  
  17.              * implementation come along?).  
  18.              */ 
  19.              if (invocation instanceof ProxyMethodInvocation) {  
  20.                 try {  
  21.                     return ((ProxyMethodInvocation) invocation).invocableClone().proceed();  
  22.                 }  
  23.                 catch (Exception e) {  
  24.                     throw e;  
  25.                 }  
  26.                 catch (Error e) {  
  27.                     throw e;  
  28.                 }  
  29.                 catch (Throwable e) {  
  30.                     throw new IllegalStateException(e);  
  31.                 }  
  32.             }  
  33.             else {  
  34.                 throw new IllegalStateException(  
  35.                         "MethodInvocation of the wrong type detected - this should not happen with Spring AOP, " +  
  36.                                 "so please raise an issue if you see this exception");  
  37.             }  
  38.         }   
  39.     };  
  40.     if (recoverer != null) {  
  41.         ItemRecovererCallback recoveryCallback = new ItemRecovererCallback(  
  42.                 invocation.getArguments(), recoverer);  
  43.         return this.retryOperations.execute(retryCallback, recoveryCallback);  
  44.     }  
  45.     //最终还是进入到retryOperations的execute方法,这个retryOperations就是在之前的builder set进来的RetryTemplate。  
  46.     return this.retryOperations.execute(retryCallback);  

无论是RetryOperationsInterceptor还是StatefulRetryOperationsInterceptor,最终的拦截处理逻辑还是调用到RetryTemplate的execute方法,从名字也看出来,RetryTemplate作为一个模板类,里面包含了重试统一逻辑。

不过,我看这个RetryTemplate并不是很“模板”,因为它没有很多可以扩展的地方。推荐阅读:最新 Spring 系列教程。

重试逻辑及策略实现

上面介绍了Spring Retry利用了AOP代理使重试机制对业务代码进行“入侵”。下面我们继续看看重试的逻辑做了什么。RetryTemplate的doExecute方法。 

  1. protected <T, E extends Throwable> T doExecute(RetryCallback<T, E> retryCallback,  
  2.    RecoveryCallback<T> recoveryCallback, RetryState state)  
  3.    throws E, ExhaustedRetryException {  
  4.     RetryPolicy retryPolicy = this.retryPolicy;  
  5.     BackOffPolicy backOffPolicy = this.backOffPolicy;  
  6.     //新建一个RetryContext来保存本轮重试的上下文  
  7.     RetryContext context = open(retryPolicy, state);  
  8.     if (this.logger.isTraceEnabled()) {  
  9.         this.logger.trace("RetryContext retrieved: " + context);  
  10.     }  
  11.     // Make sure the context is available globally for clients who need 
  12.     // it...  
  13.     RetrySynchronizationManager.register(context);  
  14.     Throwable lastException = null 
  15.     boolean exhausted = false 
  16.     try {  
  17.         //如果有注册RetryListener,则会调用它的open方法,给调用者一个通知。  
  18.         boolean running = doOpenInterceptors(retryCallback, context);  
  19.         if (!running) {  
  20.             throw new TerminatedRetryException(  
  21.                     "Retry terminated abnormally by interceptor before first attempt");  
  22.         }  
  23.         // Get or Start the backoff context...  
  24.         BackOffContext backOffContext = null 
  25.         Object resource = context.getAttribute("backOffContext");  
  26.         if (resource instanceof BackOffContext) {  
  27.             backOffContext = (BackOffContext) resource;  
  28.         }  
  29.         if (backOffContext == null) {  
  30.             backOffContext = backOffPolicy.start(context);  
  31.             if (backOffContext != null) {  
  32.                 context.setAttribute("backOffContext", backOffContext);  
  33.             }  
  34.         }  
  35.         //判断能否重试,就是调用RetryPolicy的canRetry方法来判断。  
  36.         //这个循环会直到原方法不抛出异常,或不需要再重试  
  37.         while (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) {  
  38.             try {  
  39.                 if (this.logger.isDebugEnabled()) {  
  40.                     this.logger.debug("Retry: count=" + context.getRetryCount());  
  41.                 }  
  42.                 //清除上次记录的异常  
  43.                 lastException = null 
  44.                 //doWithRetry方法,一般来说就是原方法  
  45.                 return retryCallback.doWithRetry(context);  
  46.             }  
  47.             catch (Throwable e) {  
  48.                 //原方法抛出了异常  
  49.                 lastException = e;  
  50.                 try {  
  51.                     //记录异常信息  
  52.                     registerThrowable(retryPolicy, state, context, e);  
  53.                 }  
  54.                 catch (Exception ex) {  
  55.                     throw new TerminatedRetryException("Could not register throwable",  
  56.                             ex);  
  57.                 }  
  58.                 finally {  
  59.                     //调用RetryListener的onError方法  
  60.                     doOnErrorInterceptors(retryCallback, context, e);  
  61.                 }  
  62.                 //再次判断能否重试  
  63.                 if (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) { 
  64.                     try {  
  65.                         //如果可以重试则走退避策略  
  66.                         backOffPolicy.backOff(backOffContext);  
  67.                     }  
  68.                     catch (BackOffInterruptedException ex) {  
  69.                         lastException = e;  
  70.                         // back off was prevented by another thread - fail the retry  
  71.                         if (this.logger.isDebugEnabled()) { 
  72.                              this.logger 
  73.                                      .debug("Abort retry because interrupted: count="  
  74.                                             + context.getRetryCount());  
  75.                         }  
  76.                         throw ex;  
  77.                     }  
  78.                 }  
  79.                 if (this.logger.isDebugEnabled()) {  
  80.                     this.logger.debug(  
  81.                             "Checking for rethrow: count=" + context.getRetryCount() 
  82.                 } 
  83.                 if (shouldRethrow(retryPolicy, context, state)) {  
  84.                     if (this.logger.isDebugEnabled()) { 
  85.                          this.logger.debug("Rethrow in retry for policy: count="  
  86.                                 + context.getRetryCount());  
  87.                     }  
  88.                     throw RetryTemplate.<E>wrapIfNecessary(e);  
  89.                 }  
  90.             }  
  91.             /*  
  92.              * A stateful attempt that can retry may rethrow the exception before now,  
  93.              * but if we get this far in a stateful retry there's a reason for it,  
  94.              * like a circuit breaker or a rollback classifier.  
  95.              */  
  96.             if (state != null && context.hasAttribute(GLOBAL_STATE)) {  
  97.                 break;  
  98.             }  
  99.         }  
  100.         if (state == null && this.logger.isDebugEnabled()) {  
  101.             this.logger.debug(  
  102.                     "Retry failed last attempt: count=" + context.getRetryCount());  
  103.         }  
  104.         exhausted = true 
  105.         //重试结束后如果有兜底Recovery方法则执行,否则抛异常  
  106.         return handleRetryExhausted(recoveryCallback, context, state);  
  107.     }  
  108.     catch (Throwable e) {  
  109.         throw RetryTemplate.<E>wrapIfNecessary(e);  
  110.     } 
  111.     finally {  
  112.         //处理一些关闭逻辑  
  113.         close(retryPolicy, context, state, lastException == null || exhausted);  
  114.         //调用RetryListener的close方法  
  115.         doCloseInterceptors(retryCallback, context, lastException);  
  116.         RetrySynchronizationManager.clear();  
  117.     }  

主要核心重试逻辑就是上面的代码了,看上去还是挺简单的。

在上面,我们漏掉了RetryPolicy的canRetry方法和BackOffPolicy的backOff方法,以及这两个Policy是怎么来的。我们回头看看getStatelessInterceptor方法中的getRetryPolicy和getRetryPolicy方法。 

  1. private RetryPolicy getRetryPolicy(Annotation retryable) {  
  2.     Map<String, Object> attrs = AnnotationUtils.getAnnotationAttributes(retryable);  
  3.     @SuppressWarnings("unchecked") 
  4.     Class<? extends Throwable>[] includes = (Class<? extends Throwable>[]) attrs.get("value");  
  5.     String exceptionExpression = (String) attrs.get("exceptionExpression");  
  6.     boolean hasExpression = StringUtils.hasText(exceptionExpression);  
  7.     if (includes.length == 0) {  
  8.         @SuppressWarnings("unchecked")  
  9.         Class<? extends Throwable>[] value = (Class<? extends Throwable>[]) attrs.get("include");  
  10.         includes = value 
  11.     }  
  12.     @SuppressWarnings("unchecked")  
  13.     Class<? extends Throwable>[] excludes = (Class<? extends Throwable>[]) attrs.get("exclude");  
  14.     Integer maxAttempts = (Integer) attrs.get("maxAttempts");  
  15.     String maxAttemptsExpression = (String) attrs.get("maxAttemptsExpression");  
  16.     if (StringUtils.hasText(maxAttemptsExpression)) {  
  17.         maxAttempts = PARSER.parseExpression(resolve(maxAttemptsExpression), PARSER_CONTEXT)  
  18.                 .getValue(this.evaluationContext, Integer.class);  
  19.     }  
  20.     if (includes.length == 0 && excludes.length == 0) {  
  21.         SimpleRetryPolicy simple = hasExpression ? new ExpressionRetryPolicy(resolve(exceptionExpression))  
  22.                                                         .withBeanFactory(this.beanFactory)  
  23.                                                  : new SimpleRetryPolicy();  
  24.         simple.setMaxAttempts(maxAttempts);  
  25.         return simple;  
  26.     }  
  27.     Map<Class<? extends Throwable>, Boolean> policyMap = new HashMap<Class<? extends Throwable>, Boolean>();  
  28.     for (Class<? extends Throwable> type : includes) {  
  29.         policyMap.put(type, true);  
  30.     }  
  31.     for (Class<? extends Throwable> type : excludes) {  
  32.         policyMap.put(type, false);  
  33.     }  
  34.     boolean retryNotExcluded = includes.length == 0;  
  35.     if (hasExpression) {  
  36.         return new ExpressionRetryPolicy(maxAttempts, policyMap, true, exceptionExpression, retryNotExcluded)  
  37.                 .withBeanFactory(this.beanFactory);  
  38.     }  
  39.     else {  
  40.         return new SimpleRetryPolicy(maxAttempts, policyMap, true, retryNotExcluded);  
  41.     }  
  42.  
  43. 嗯~,代码不难,这里简单做一下总结好了。就是通过@Retryable注解中的参数,来判断具体使用文章开头说到的哪个重试策略,是SimpleRetryPolicy还是ExpressionRetryPolicy等。  
  44. private BackOffPolicy getBackoffPolicy(Backoff backoff) {  
  45.     long min = backoff.delay() == 0 ? backoff.value() : backoff.delay();  
  46.     if (StringUtils.hasText(backoff.delayExpression())) {  
  47.         min = PARSER.parseExpression(resolve(backoff.delayExpression()), PARSER_CONTEXT)  
  48.                 .getValue(this.evaluationContext, Long.class);  
  49.     }  
  50.     long max = backoff.maxDelay();  
  51.     if (StringUtils.hasText(backoff.maxDelayExpression())) {  
  52.         max = PARSER.parseExpression(resolve(backoff.maxDelayExpression()), PARSER_CONTEXT)  
  53.                 .getValue(this.evaluationContext, Long.class);  
  54.     }  
  55.     double multiplier = backoff.multiplier();  
  56.     if (StringUtils.hasText(backoff.multiplierExpression())) {  
  57.         multiplier = PARSER.parseExpression(resolve(backoff.multiplierExpression()), PARSER_CONTEXT)  
  58.                 .getValue(this.evaluationContext, Double.class);  
  59.     }  
  60.     if (multiplier > 0) {  
  61.         ExponentialBackOffPolicy policy = new ExponentialBackOffPolicy();  
  62.         if (backoff.random()) {  
  63.             policy = new ExponentialRandomBackOffPolicy();  
  64.         }  
  65.         policy.setInitialInterval(min);  
  66.         policy.setMultiplier(multiplier);  
  67.         policy.setMaxInterval(max > min ? max : ExponentialBackOffPolicy.DEFAULT_MAX_INTERVAL);  
  68.         if (this.sleeper != null) {  
  69.             policy.setSleeper(this.sleeper);  
  70.         }  
  71.         return policy;  
  72.     }  
  73.     if (max > min) {  
  74.         UniformRandomBackOffPolicy policy = new UniformRandomBackOffPolicy();  
  75.         policy.setMinBackOffPeriod(min);  
  76.         policy.setMaxBackOffPeriod(max);  
  77.         if (this.sleeper != null) {  
  78.             policy.setSleeper(this.sleeper);  
  79.         }  
  80.         return policy;  
  81.     }  
  82.     FixedBackOffPolicy policy = new FixedBackOffPolicy();  
  83.     policy.setBackOffPeriod(min);  
  84.     if (this.sleeper != null) { 
  85.          policy.setSleeper(this.sleeper);  
  86.     }  
  87.     return policy;  

嗯~,一样的味道。就是通过@Backoff注解中的参数,来判断具体使用文章开头说到的哪个退避策略,是FixedBackOffPolicy还是UniformRandomBackOffPolicy等。

那么每个RetryPolicy都会重写canRetry方法,然后在RetryTemplate判断是否需要重试。我们看看SimpleRetryPolicy的 

  1. @Override  
  2. public boolean canRetry(RetryContext context) {  
  3.     Throwable t = context.getLastThrowable();  
  4.     //判断抛出的异常是否符合重试的异常  
  5.     //还有,是否超过了重试的次数  
  6.     return (t == null || retryForException(t)) && context.getRetryCount() < maxAttempts 

同样,我们看看FixedBackOffPolicy的退避方法。 

  1. protected void doBackOff() throws BackOffInterruptedException {  
  2.     try {  
  3.         //就是sleep固定的时间  
  4.         sleeper.sleep(backOffPeriod); 
  5.      }  
  6.     catch (InterruptedException e) {  
  7.         throw new BackOffInterruptedException("Thread interrupted while sleeping", e); 
  8.     }  

至此,重试的主要原理以及逻辑大概就是这样了。

RetryContext

我觉得有必要说说RetryContext,先看看它的继承关系。

可以看出对每一个策略都有对应的Context。

在Spring Retry里,其实每一个策略都是单例来的。我刚开始直觉是对每一个需要重试的方法都会new一个策略,这样重试策略之间才不会产生冲突,但是一想就知道这样就可能多出了很多策略对象出来,增加了使用者的负担,这不是一个好的设计。

Spring Retry采用了一个更加轻量级的做法,就是针对每一个需要重试的方法只new一个上下文Context对象,然后在重试时,把这个Context传到策略里,策略再根据这个Context做重试,而且Spring Retry还对这个Context做了cache。这样就相当于对重试的上下文做了优化。

总结

Spring Retry通过AOP机制来实现对业务代码的重试”入侵“,RetryTemplate中包含了核心的重试逻辑,还提供了丰富的重试策略和退避策略。

最后,关注公众号Java技术栈,在后台回复:面试,可以获取我整理的 Spring 系列面试题和答案,非常齐全。 

 

责任编辑:庞桂玉 来源: Java技术栈
相关推荐

2022-11-14 08:19:59

重试机制Kafka

2020-07-19 15:39:37

Python开发工具

2022-05-06 07:44:10

微服务系统设计重试机制

2023-10-27 08:20:12

springboot微服务

2017-07-02 16:50:21

2017-06-16 15:16:15

2023-11-27 07:44:59

RabbitMQ机制

2024-01-04 18:01:55

高并发SpringBoot

2023-11-06 08:00:38

接口高可用机制

2024-04-02 09:32:08

Spring@Retry开发者

2018-07-12 15:30:03

HTTP缓存机制

2020-12-11 11:26:47

Spring批处理重试

2009-06-24 10:58:21

jQuery插件教程

2023-10-17 08:01:46

MQ消息重试

2023-11-17 11:55:54

Pythonretrying库

2020-08-19 09:45:29

Spring数据库代码

2023-10-30 07:36:19

Spring事务传播机制

2023-06-06 07:50:07

权限管理hdfsacl

2010-08-27 10:12:53

CSS

2011-03-31 11:40:13

SQL
点赞
收藏

51CTO技术栈公众号