欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解Spring Cloud Zuul重试机制探秘

程序员文章站 2023-12-18 14:33:46
简介 本文章对应spring cloud的版本为(dalston.sr4),具体内容如下: 开启zuul功能 通过源码了解zuul的一次转发 怎么开...

简介

本文章对应spring cloud的版本为(dalston.sr4),具体内容如下:

  1. 开启zuul功能
  2. 通过源码了解zuul的一次转发
  3. 怎么开启zuul的重试机制
  4. edgware.rc1版本的优化

开启zuul的功能

首先如何使用spring cloud zuul完成路由转发的功能,这个问题很简单,只需要进行如下准备工作即可:

  1. 注册中心(eureka server)
  2. zuul(同时也是eureka client)
  3. 应用服务(同时也是eureka client)

我们希望zuul和后端的应用服务同时都注册到eureka server上,当我们访问zuul的某一个地址时,对应其实访问的是后端应用的某个地址,从而从这个地址返回一段内容,并展现到浏览器上。

注册中心(eureka server)

创建一个eureka server只需要在主函数上添加@enableeurekaserver,并在properties文件进行简单配置即可,具体内容如下:

@enableeurekaserver
@restcontroller
@springbootapplication
public class eurekaserverapplication {
  public static void main(string[] args) {
   springapplication.run(eurekaserverapplication.class, args);
  }
}
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

zuul

主函数添加@enablezuulproxy注解(因为集成eureka,需要另外添加@enablediscoveryclient注解)。并配置properties文件,具体内容如下所示:

@enablezuulproxy
@enablediscoveryclient
@springbootapplication
public class zuuldemoapplication {
  /**
  * 省略代码...
  */
}
server.port=8081
spring.application.name=zuul-client
zuul.routes.api-a.serviceid=eureka-client
zuul.routes.api-a.path=/api-a/**
eureka.client.service-url.defaultzone=http://localhost:8761/eureka

应用服务

@restcontroller
@enableeurekaclient
@springbootapplication
public class eurekaclientapplication {
  public static void main(string[] args) {
   springapplication.run(eurekaclientapplication.class, args);
  }
  @requestmapping(value = "/hello")
  public string index() {
   return "hello spring...";
  }
}
 
spring.application.name=eureka-client
eureka.client.service-url.defaultzone=http://localhost:8761/eureka

三个工程全部启动,这时当我们访问localhost:8081/api-a/hello时,你会看到浏览器输出的内容是hello spring...

通过源码了解zuul的一次转发

接下来我们通过源码层面来了解下,一次转发内部都做了哪些事情。

首先我们查看zuul的配置类zuulproxyautoconfiguration在这个类中有一项工作是初始化zuul默认自带的filter,其中有一个filter很重要,它就是ribbonroutingfilter。它主要是完成请求的路由转发。接下来我们看下他的run方法

@override
public object run() {
  requestcontext context = requestcontext.getcurrentcontext();
  try {
   ribboncommandcontext commandcontext = buildcommandcontext(context);
   clienthttpresponse response = forward(commandcontext);
   setresponse(response);
   return response;
  }
  catch (zuulexception ex) {
   throw new zuulruntimeexception(ex);
  }
  catch (exception ex) {
   throw new zuulruntimeexception(ex);
  }
}

可以看到进行转发的方法是forward,我们进一步查看这个方法,具体内容如下:

省略部分代码

protected clienthttpresponse forward(ribboncommandcontext context) throws exception {
  ribboncommand command = this.ribboncommandfactory.create(context);
  try {
   clienthttpresponse response = command.execute();
   return response;
  }
  catch (hystrixruntimeexception ex) {
   return handleexception(info, ex);
  }
}

ribboncommandfactory指的是httpclientribboncommandfactory这个类是在ribboncommandfactoryconfiguration完成初始化的(触发ribboncommandfactoryconfiguration的加载动作是利用zuulproxyautoconfiguration类上面的@import标签),具体代码如下:

@configuration
@conditionalonribbonhttpclient
protected static class httpclientribbonconfiguration {
  @autowired(required = false)
  private set<zuulfallbackprovider> zuulfallbackproviders = collections.emptyset();
  @bean
  @conditionalonmissingbean
  public ribboncommandfactory<?> ribboncommandfactory(
     springclientfactory clientfactory, zuulproperties zuulproperties) {
   return new httpclientribboncommandfactory(clientfactory, zuulproperties, zuulfallbackproviders);
  }
}

知道了这个ribboncommandfactory具体的实现类(httpclientribboncommandfactory),接下来我们看看它的create方法具体做了那些事情

@override
public httpclientribboncommand create(final ribboncommandcontext context) {
  zuulfallbackprovider zuulfallbackprovider = getfallbackprovider(context.getserviceid());
  final string serviceid = context.getserviceid();
  final ribbonloadbalancinghttpclient client = this.clientfactory.getclient(
     serviceid, ribbonloadbalancinghttpclient.class);
  client.setloadbalancer(this.clientfactory.getloadbalancer(serviceid));
  return new httpclientribboncommand(serviceid, client, context, zuulproperties, zuulfallbackprovider,
     clientfactory.getclientconfig(serviceid));
}

这个方法按照我的理解主要做了以下几件事情:

@override
public httpclientribboncommand create(final ribboncommandcontext context) {
  /**
  *获取所有zuulfallbackprovider,即当zuul
  *调用失败后的降级方法
  */
  zuulfallbackprovider = xxxxx
  /**
  *创建处理请求转发类,该类会利用
  *apache的http client进行请求的转发
  */
  ribbonloadbalancinghttpclient = xxxxx
  
  /**
  *将降级方法、处理请求转发类、以及其他一些内容
  *包装成httpclientribboncommand(这个类继承了hystrixcommand)
  */
  return new httpclientribboncommand(xxxxx);
}

到这里我们很清楚的知道了ribbonroutingfilter类的forward方法中ribboncommand command = this.ribboncommandfactory.create(context);这一行代码都做了哪些内容.

接下来调用的是command.execute();方法,通过刚刚的分析我们知道了command其实指的是httpclientribboncommand,同时我们也知道httpclientribboncommand继承了hystrixcommand所以当执行command.execute();时其实执行的是httpclientribboncommand的run方法。查看源码我们并没有发现run方法,但是我们发现httpclientribboncommand直接继承了abstractribboncommand。所以其实执行的是abstractribboncommand的run方法,接下来我们看看run方法里面都做了哪些事情:

@override
protected clienthttpresponse run() throws exception {
  final requestcontext context = requestcontext.getcurrentcontext();
  rq request = createrequest();
  rs response = this.client.executewithloadbalancer(request, config);
  context.set("ribbonresponse", response);
  if (this.isresponsetimedout()) {
   if (response != null) {
     response.close();
   }
  }
  return new ribbonhttpresponse(response);
}

可以看到在run方法中会调用client的executewithloadbalancer方法,通过上面介绍我们知道client指的是ribbonloadbalancinghttpclient,而ribbonloadbalancinghttpclient里面并没有executewithloadbalancer方法。(这里面会最终调用它的父类abstractloadbalancerawareclient的executewithloadbalancer方法。)

具体代码如下:

public t executewithloadbalancer(final s request, final iclientconfig requestconfig) throws clientexception {
 /**
 * 创建一个retryhandler,这个很重要它是用来
 * 决定利用rxjava的observable是否进行重试的标准。
 */
  requestspecificretryhandler handler = getrequestspecificretryhandler(request, requestconfig);
  /**
   * 创建一个loadbalancercommand,这个类用来创建observable
   * 以及根据retryhandler来判断是否进行重试操作。
   */
  loadbalancercommand<t> command = loadbalancercommand.<t>builder()
      .withloadbalancercontext(this)
      .withretryhandler(handler)
      .withloadbalanceruri(request.geturi())
      .build();
  try {
   /**
   *command.submit()方法主要是创建了一个observable(rxjava)
   *并且为这个observable设置了重试次数,这个observable最终
   *会回调abstractloadbalancerawareclient.this.execute()
   *方法。
   */
    return command.submit(
      new serveroperation<t>() {
        @override
        public observable<t> call(server server) {
          uri finaluri = reconstructuriwithserver(server, request.geturi());
          s requestforserver = (s) request.replaceuri(finaluri);
          try {
            return observable.just(abstractloadbalancerawareclient.this.execute(requestforserver, requestconfig));
          } 
          catch (exception e) {
            return observable.error(e);
          }
        }
      })
      .toblocking()
      .single();
  } catch (exception e) {
    throwable t = e.getcause();
    if (t instanceof clientexception) {
      throw (clientexception) t;
    } else {
      throw new clientexception(e);
    }
  }
  
}

下面针对于每一块内容做详细说明:

首先getrequestspecificretryhandler(request, requestconfig);这个方法其实调用的是ribbonloadbalancinghttpclient的getrequestspecificretryhandler方法,这个方法主要是返回一个requestspecificretryhandler

@override
public requestspecificretryhandler getrequestspecificretryhandler(ribbonapachehttprequest request, iclientconfig requestconfig) {
 /**
 *这个很关键,请注意该类构造器中的前两个参数的值
 *正因为一开始我也忽略了这两个值,所以后续给我造
 *成一定的干扰。
 */
  return new requestspecificretryhandler(false, false,
     retryhandler.default, requestconfig);
}

接下来创建loadbalancercommand并将上一步获得的requestspecificretryhandler作为参数内容。

最后调用loadbalancercommand的submit方法。该方法内容太长具体代码细节就不在这里贴出了,按照我个人的理解,只贴出相应的伪代码:

public observable<t> submit(final serveroperation<t> operation) {
 //相同server的重试次数(去除首次请求)
  final int maxretryssame = retryhandler.getmaxretriesonsameserver();
  //集群内其他server的重试个数
  final int maxretrysnext = retryhandler.getmaxretriesonnextserver();
  /**
   *创建一个observable(rxjava),selectserver()方法是
   *利用ribbon选择一个server,并将其包装成observable
   */
  observable<t> o = selectserver().concatmap(new func1<server, observable<t>>() { 
    @override
    public observable<t> call(final server server) {
     /**
     *这里会回调submit方法入参serveroperation类的call方法,
     */
   return operation.call(server).dooneach(new observer<t>() {}
 }
  }
  if (maxretryssame > 0) 
   o = o.retry(retrypolicy(maxretryssame, true));
    
  if (maxretrysnext > 0 && server == null) 
    o = o.retry(retrypolicy(maxretrysnext, false));
  
  return o.onerrorresumenext(new func1<throwable, observable<t>>() {
    @override
    public observable<t> call(throwable e) {
    /**
    *转发请求失败时,会进入此方法。通过此方法进行判断
    *是否超过重试次数maxretryssame、maxretrysnext。
    */
   }
  });
}

operation.call()方法最终会调用ribbonloadbalancinghttpclient的execute方法,该方法内容如下:

@override
public ribbonapachehttpresponse execute(ribbonapachehttprequest request,
   final iclientconfig configoverride) throws exception {
  /**
  * 组装参数(requestconfig)
  */
  final requestconfig.builder builder = requestconfig.custom();
  iclientconfig config = configoverride != null ? configoverride : this.config;
  builder.setconnecttimeout(config.get(
     commonclientconfigkey.connecttimeout, this.connecttimeout));
  builder.setsockettimeout(config.get(
     commonclientconfigkey.readtimeout, this.readtimeout));
  builder.setredirectsenabled(config.get(
     commonclientconfigkey.followredirects, this.followredirects));
  final requestconfig requestconfig = builder.build();
  if (issecure(configoverride)) {
   final uri secureuri = uricomponentsbuilder.fromuri(request.geturi())
      .scheme("https").build().touri();
   request = request.withnewuri(secureuri);
  }
  final httpurirequest httpurirequest = request.torequest(requestconfig);
  /**
  * 发送转发请求
  */
  final httpresponse httpresponse = this.delegate.execute(httpurirequest);
  /**
  * 返回结果
  */
  return new ribbonapachehttpresponse(httpresponse, httpurirequest.geturi());
}

可以看到上面方法主要做的就是组装请求参数(包括各种超时时间),然后发起转发请求,最终获取相应结果。

说到这里,zuul转发一次请求的基本原理就说完了。让我们再回顾下整个流程。

  1. zuul的转发是通过ribbonroutingfilter这个filter进行操作的。
  2. 在转发之前,zuul利用hystrix将此次转发请求包装成一个hystrixcommand,正应为这样才使得zuul具有了降级(fallback)的功能,同时hystrixcommand是具备超时时间的(默认是1s)。而且zuul默认采用的隔离级别是信号量模式。
  3. 在hystrixcommand内部zuul再次将请求包装成一个observable,(有关rxjava的知识请参照其官方文档)。并且为observable设置了重试次数。

事实真的是这样吗?当我看到源码中为observable设置重试次数的时候,我以为这就是zuul的重试逻辑。遗憾的是我的想法是错误的。还记得上面我说的getrequestspecificretryhandler(request, requestconfig);这个方法吗?(不记得的同学可以回过头来再看下),这个方法返回的是requestspecificretryhandler这个类,而且在创建该类时,构造器的前两个参数都为false。(这一点非常重要)。这两个参数分别是oktoretryonconnecterrors和oktoretryonallerrors。

我原本的想法是这个请求被包装成observable,如果这次请求因为超时出现异常或者其他异常,这样就会触发observable的重试机制(rxjava),但是事实并非如此,为什么呢?原因就是上面的那两个参数,当出现了超时异常的时候,在触发重试机制之前会调用requestspecificretryhandler的isretriableexception()方法,该方法的作用是用来判断是否执行重试动作,具体代码如下:

@override
public boolean isretriableexception(throwable e, boolean sameserver) {
  //此时该值为false
  if (oktoretryonallerrors) {
    return true;
  } 
  else if (e instanceof clientexception) {
    clientexception ce = (clientexception) e;
    if (ce.geterrortype() == clientexception.errortype.server_throttled) {
      return !sameserver;
    } else {
      return false;
    }
  } 
  else {
    //此时该值为false
    return oktoretryonconnecterrors && isconnectionexception(e);
  }
}

说道这里zuul转发一次请求的基本原理大概了解了,同时也验证了一个事实就是实现zuul进行重试的逻辑并不是observable的重试机制。那么问题来了?是什么使zuul具有重试功能的呢?

怎么开启zuul的重试机制

开启zuul重试的功能在原有的配置基础上需要额外进行以下设置:

  1. 在pom中添加spring-retry的依赖(maven工程)
  2. 设置zuul.retryable=true(该参数默认为false)

具体properties文件内容如下:

server.port=8081
spring.application.name=zuul-client
#路由信息
zuul.routes.api-a.serviceid=eureka-client
zuul.routes.api-a.path=/api-a/**
#是否开启重试功能
zuul.retryable=true
#同一个server重试的次数(除去首次)
ribbon.maxautoretries=3
#切换相同server的次数
ribbon.maxautoretriesnextserver=0
eureka.client.service-url.defaultzone=http://localhost:8761/eureka

为了模拟出zuul重试的功能,需要对后端应用服务进行改造,改造后的内容如下:

@requestmapping(value = "/hello")
public string index() {
  system.out.println("request is coming...");
  try {
   thread.sleep(100000);
  } catch (interruptedexception e) {
   system.out.println("线程被打断... " + e.getmessage());
  }
  return "hello spring ...";
}

通过使用thread.sleep(100000)达到zuul转发超时情况(zuul默认连接超时未2s、read超时时间为5s),从而触发zuul的重试功能。这时候在此访问localhost:8081/api-a/hello时,查看应用服务后台,会发现最终打印三次"request is coming..."

通过现象看本质,接下来简单介绍下zuul重试的原理。首先如果你工程classpath中存在spring-retry,那么zuul在初始化的时候就不会创建ribbonloadbalancinghttpclient而是创建retryableribbonloadbalancinghttpclient具体源代码如下:

@conditionalonclass(name = "org.apache.http.client.httpclient")
@conditionalonproperty(name = "ribbon.httpclient.enabled", matchifmissing = true)
public class httpclientribbonconfiguration {
  @value("${ribbon.client.name}")
  private string name = "client";
  @bean
  @conditionalonmissingbean(abstractloadbalancerawareclient.class)
  @conditionalonmissingclass(value = "org.springframework.retry.support.retrytemplate")
  public ribbonloadbalancinghttpclient ribbonloadbalancinghttpclient(
     iclientconfig config, serverintrospector serverintrospector,
     iloadbalancer loadbalancer, retryhandler retryhandler) {
   ribbonloadbalancinghttpclient client = new ribbonloadbalancinghttpclient(
      config, serverintrospector);
   client.setloadbalancer(loadbalancer);
   client.setretryhandler(retryhandler);
   monitors.registerobject("client_" + this.name, client);
   return client;
  }
  @bean
  @conditionalonmissingbean(abstractloadbalancerawareclient.class)
  @conditionalonclass(name = "org.springframework.retry.support.retrytemplate")
  public retryableribbonloadbalancinghttpclient retryableribbonloadbalancinghttpclient(
     iclientconfig config, serverintrospector serverintrospector,
     iloadbalancer loadbalancer, retryhandler retryhandler,
     loadbalancedretrypolicyfactory loadbalancedretrypolicyfactory) {
   retryableribbonloadbalancinghttpclient client = new retryableribbonloadbalancinghttpclient(
      config, serverintrospector, loadbalancedretrypolicyfactory);
   client.setloadbalancer(loadbalancer);
   client.setretryhandler(retryhandler);
   monitors.registerobject("client_" + this.name, client);
   return client;
  }
}

所以请求到来需要转发的时候(abstractloadbalancerawareclient类中executewithloadbalancer方法会调用abstractloadbalancerawareclient.this.execute())其实调用的是retryableribbonloadbalancinghttpclient的execute方法(而不是没有重试时候ribbonloadbalancinghttpclient的execute方法),源码内容如下:

@override
public ribbonapachehttpresponse execute(final ribbonapachehttprequest request, final iclientconfig configoverride) throws exception {
  final requestconfig.builder builder = requestconfig.custom();
  iclientconfig config = configoverride != null ? configoverride : this.config;
  builder.setconnecttimeout(config.get(
     commonclientconfigkey.connecttimeout, this.connecttimeout));
  builder.setsockettimeout(config.get(
     commonclientconfigkey.readtimeout, this.readtimeout));
  builder.setredirectsenabled(config.get(
     commonclientconfigkey.followredirects, this.followredirects));
  final requestconfig requestconfig = builder.build();
  final loadbalancedretrypolicy retrypolicy = loadbalancedretrypolicyfactory.create(this.getclientname(), this);
  retrycallback retrycallback = new retrycallback() {
   @override
   public ribbonapachehttpresponse dowithretry(retrycontext context) throws exception {
     //on retries the policy will choose the server and set it in the context
     //extract the server and update the request being made
     ribbonapachehttprequest newrequest = request;
     if(context instanceof loadbalancedretrycontext) {
      serviceinstance service = ((loadbalancedretrycontext)context).getserviceinstance();
      if(service != null) {
        //reconstruct the request uri using the host and port set in the retry context
        newrequest = newrequest.withnewuri(new uri(service.geturi().getscheme(),
           newrequest.geturi().getuserinfo(), service.gethost(), service.getport(),
           newrequest.geturi().getpath(), newrequest.geturi().getquery(),
           newrequest.geturi().getfragment()));
      }
     }
     if (issecure(configoverride)) {
      final uri secureuri = uricomponentsbuilder.fromuri(newrequest.geturi())
         .scheme("https").build().touri();
      newrequest = newrequest.withnewuri(secureuri);
     }
     httpurirequest httpurirequest = newrequest.torequest(requestconfig);
     final httpresponse httpresponse = retryableribbonloadbalancinghttpclient.this.delegate.execute(httpurirequest);
     if(retrypolicy.retryablestatuscode(httpresponse.getstatusline().getstatuscode())) {
      if(closeablehttpresponse.class.isinstance(httpresponse)) {
        ((closeablehttpresponse)httpresponse).close();
      }
      throw new retryablestatuscodeexception(retryableribbonloadbalancinghttpclient.this.clientname,
         httpresponse.getstatusline().getstatuscode());
     }
     return new ribbonapachehttpresponse(httpresponse, httpurirequest.geturi());
   }
  };
  return this.executewithretry(request, retrypolicy, retrycallback);
}

executewithretry方法内容如下:

private ribbonapachehttpresponse executewithretry(ribbonapachehttprequest request, loadbalancedretrypolicy retrypolicy, retrycallback<ribbonapachehttpresponse, ioexception> callback) throws exception {
  retrytemplate retrytemplate = new retrytemplate();
  boolean retryable = request.getcontext() == null ? true :
     booleanutils.tobooleandefaultifnull(request.getcontext().getretryable(), true);
  retrytemplate.setretrypolicy(retrypolicy == null || !retryable ? new neverretrypolicy()
     : new retrypolicy(request, retrypolicy, this, this.getclientname()));
  return retrytemplate.execute(callback);
}

按照我的理解,主要逻辑如下:

@override
public ribbonapachehttpresponse execute(final ribbonapachehttprequest request, final iclientconfig configoverride) throws exception {
  /**
  *创建requestconfig(请求信息)
  */
  final requestconfig requestconfig = builder.build();
  final loadbalancedretrypolicy retrypolicy =       loadbalancedretrypolicyfactory.create(this.getclientname(), this);
  /**
  * 创建retrycallbck的实现类,用来完成重试逻辑
  */
  retrycallback retrycallback = new retrycallback() {};
  
  //创建spring-retry的模板类,retrytemplate。
  retrytemplate retrytemplate = new retrytemplate();
 /**
 *设置重试规则,即在什么情况下进行重试
 *什么情况下停止重试。源码中这部分存在
 *一个判断,判断的根据就是在zuul工程
 *的propertris中配置的zuul.retryable
 *该参数内容为true才可以具有重试功能。
 */
 retrytemplate.setretrypolicy(xxx);
 /**
 *发起请求
 */
 return retrytemplate.execute(callback);
}

到此为止我们不仅知道了zuul路由一次请求的整体过程,也明确了zuul因后端超时而触发重试的原理。可是似乎还存在着一个问题,就是超时问题。前面说过zuul把路由请求这个过程包装成一个hystrixcommnd,而在我的propertries文件中并没有设置hystrix的超时时间(默认时间为1s),而read的超时时间是5s(前面源码部分介绍过)。这里就会有人问,因为最外层是采用hystrix,而hystrix此时已经超时了,为什么还允许它内部继续使用spring-retry进行重试呢?带着这个问题我查看了官方github上的issues,发现有人对此问题提出过疑问。作者给出的回复是hystrix超时的时候并不会打断内部重试的操作。

其实说实话这块内容我并不是很理解(可能是因为hystrix源码了解较少),带着这个问题我给作者发了一封邮件,邮件对话内容如下:

我的(英语水平不好,大家见谅):

i want to confirm two issues with you, first of all zuul retry only spring-retry exists and zuul.retry this parameter is true to take effect? the second problem is that if my classpath spring-retry at the same time i let zuul.retry this parameter is true, which means that at this time zuul have a retry mechanism, then why when hystrix time-out can not interrupt the spring- retry it. thank you very much

作者的回复(重点):

zuul will retry failed requests if spring retry is on the classpath and the property zuul.retryable is set to true. the retry is happening within the hystrix command, so if hystrix times out than a response is returned. right now there is no mechanism to stop further retries from happening if hystrix times out before all the retries are exhauted.
on thu, nov 16, 2017 at 8:40 am 李刚 spring_holy@163.com wrote:

虽然得到了作者的确认,但是这部分内容始终还是没有完全理解,后续还要看看hystrix的源码。

edgware.rc1版本的优化

在edgware.rc1版本中,作者修改了代码并不使用ribbon的默认值而是将connecttimeout以及readtimeout都赋值为1s),,同时调整hystrix的超时时间,时间为(2s).具体信息内容如下:

同时作者也阐明了利用hystrix包装使用ribbon时关于超时时间的设置规则(以下内容来自github):

when using hystrix commands that wrap ribbon clients you want to make sure your hystrix timeout is configured to be longer than the configured ribbon timeout, including any potential
retries that might be made. for example, if your ribbon connection timeout is one second and
the ribbon client might retry the request three times, than your hystrix timeout should
be slightly more than three seconds.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持

上一篇:

下一篇: