专栏名称: 亿级流量网站架构
开涛技术点滴
目录
相关文章推荐
蚂蚁技术AntTech  ·  欢迎参加!蚂蚁SRC年度颁奖盛典&大模型安全交流会 ·  5 小时前  
京东科技技术说  ·  Taro on Harmony C-API ... ·  2 天前  
码农翻身  ·  投诉领导被光速开除,和烂人说再见啦~ ·  2 天前  
51好读  ›  专栏  ›  亿级流量网站架构

spring-retry重试与熔断详解—《亿级流量》内容补充

亿级流量网站架构  · 公众号  · 程序员  · 2017-05-01 11:01

正文

请到「今天看啥」查看全文


, E > retryCallback,
RecoveryCallback<
T > recoveryCallback, RetryState state)
throws E , ExhaustedRetryException {
// 重试策略
RetryPolicy retryPolicy = this . retryPolicy ;

   //退避策略
   BackOffPolicy backOffPolicy = this.backOffPolicy;
   //重试上下文,当前重试次数等都记录在上下文中
   RetryContext context = open(retryPolicy, state);
  
try {

      //拦截器模式,执行RetryListener#open
      boolean running = doOpenInterceptors(retryCallback, context);

      //判断是否可以重试执行
      while (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) {
        
try {//执行RetryCallback回调
            return retryCallback.doWithRetry(context);
         }
catch (Throwable e) {//异常时,要进行下一次重试准备

            //遇到异常后,注册该异常的失败次数
            registerThrowable(retryPolicy, state, context, e);

            //执行RetryListener#onError
            doOnErrorInterceptors(retryCallback, context, e);

            //如果可以重试,执行退避算法,比如休眠一小段时间后再重试
            if (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) {
               backOffPolicy.backOff(backOffContext);
            }

            //state != null && state.rollbackFor(context.getLastThrowable())

            //在有状态重试时,如果是需要执行回滚操作的异常,则立即抛出异常
            if (shouldRethrow(retryPolicy, context, state)) {
              
throw RetryTemplate.<E>wrapIfNecessary(e);
            }
         }

         //如果是有状态重试,且有GLOBAL_STATE属性,则立即跳出重试终止;当抛出的异常是非需要执行回滚操作的异常时,才会执行到此处,CircuitBreakerRetryPolicy会在此跳出循环;
         if (state != null && context.hasAttribute(GLOBAL_STATE)) {
           
break;
         }
      }

      //重试失败后,如果有RecoveryCallback,则执行此回调,否则抛出异常
      return handleRetryExhausted(recoveryCallback, context, state);
   }
catch (Throwable e) {
     
throw RetryTemplate.<E>wrapIfNecessary(e);
   }
finally {

      //清理环境
      close(retryPolicy, context, state, lastException == null || exhausted);

      //执行RetryListener#close,比如统计重试信息
      doCloseInterceptors(retryCallback, context, lastException);
   }
}

有状态or无状态

无状态重试,是在一个循环中执行完重试策略,即重试上下文保持在一个线程上下文中,在一次调用中进行完整的重试策略判断。







请到「今天看啥」查看全文