溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring-cloud Feign的示例分析

發(fā)布時(shí)間:2021-09-03 11:26:06 來源:億速云 閱讀:187 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)Spring-cloud Feign的示例分析的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

feign的調(diào)用流程

讀取注解信息:EnableFeignClients-->FeignClientsRegistrar-->FeignClientFactoryBean
feigh流程:ReflectiveFeign-->Contract-->SynchronousMethodHandler
相關(guān)configuration:FeignClientsConfiguration,F(xiàn)eignAutoConfiguration,DefaultFeignLoadBalancedConfiguration,F(xiàn)eignRibbonClientAutoConfiguration(Ribbon)

在FeignClientsRegistrar中:

  @Override
  public void registerBeanDefinitions(AnnotationMetadata metadata,
      BeanDefinitionRegistry registry) {
    //注冊(cè)feign配置信息
    registerDefaultConfiguration(metadata, registry);
    //注冊(cè)feign client
    registerFeignClients(metadata, registry);
  }

  private void registerFeignClient(BeanDefinitionRegistry registry,
      AnnotationMetadata annotationMetadata, Map<String, Object> attributes) {
    String className = annotationMetadata.getClassName();
    //準(zhǔn)備注入FeignClientFactoryBean
    BeanDefinitionBuilder definition = BeanDefinitionBuilder
        .genericBeanDefinition(FeignClientFactoryBean.class);
    ...
  }

查看FeignClientFactoryBean:

  @Override
  public Object getObject() throws Exception {
    FeignContext context = applicationContext.getBean(FeignContext.class);
    //構(gòu)建Feign.Builder
    Feign.Builder builder = feign(context);
    //如果注解沒有指定URL
    if (!StringUtils.hasText(this.url)) {
      String url;
      if (!this.name.startsWith("http")) {
        url = "http://" + this.name;
      }
      else {
        url = this.name;
      }
      url += cleanPath();
      return loadBalance(builder, context, new HardCodedTarget<>(this.type,
          this.name, url));
    }
    //如果指定了URL
    if (StringUtils.hasText(this.url) && !this.url.startsWith("http")) {
      this.url = "http://" + this.url;
    }
    String url = this.url + cleanPath();
    Client client = getOptional(context, Client.class);
    if (client != null) {
      if (client instanceof LoadBalancerFeignClient) {
        // 因?yàn)橹付薝RL且classpath下有Ribbon,獲取client的delegate(unwrap)
        // not load balancing because we have a url,
        // but ribbon is on the classpath, so unwrap
        client = ((LoadBalancerFeignClient)client).getDelegate();
      }
      builder.client(client);
    }
    Targeter targeter = get(context, Targeter.class);
    return targeter.target(this, builder, context, new HardCodedTarget<>(
        this.type, this.name, url));
  }
  
  protected <T> T loadBalance(Feign.Builder builder, FeignContext context,
      HardCodedTarget<T> target) {
    //獲取Feign Client實(shí)例
    Client client = getOptional(context, Client.class);
    if (client != null) {
      builder.client(client);
      //DefaultTargeter或者HystrixTargeter
      Targeter targeter = get(context, Targeter.class);
      //調(diào)用builder的target,其中就調(diào)用了Feign的newInstance
      return targeter.target(this, builder, context, target);
    }

    throw new IllegalStateException(
        "No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-netflix-ribbon?");
  }

在FeignClientsConfiguration配置了Feign.Builder,prototype類型:

  @Bean
  @Scope("prototype")
  @ConditionalOnMissingBean
  public Feign.Builder feignBuilder(Retryer retryer) {
    return Feign.builder().retryer(retryer);
  }

Feign的Builder.build返回了一個(gè)ReflectiveFeign:

  public Feign build() {
   SynchronousMethodHandler.Factory synchronousMethodHandlerFactory =
     new SynchronousMethodHandler.Factory(client, retryer, requestInterceptors, logger,
                        logLevel, decode404);
   ParseHandlersByName handlersByName =
     new ParseHandlersByName(contract, options, encoder, decoder,
                 errorDecoder, synchronousMethodHandlerFactory);
   //ReflectiveFeign構(gòu)造參數(shù)
   //ParseHandlersByName作用是通過傳入的target返回代理接口下的方法的各種信息(MethodHandler)
   //Contract:解析接口的方法注解規(guī)則,生成MethodMetadata
   //Options:Request超時(shí)配置
   //Encoder:請(qǐng)求編碼器
   //Decoder:返回解碼器
   //ErrorDecoder:錯(cuò)誤解碼器
   //SynchronousMethodHandler.Factory是構(gòu)建SynchronousMethodHandler的工廠
   //Client:代表真正執(zhí)行HTTP的組件
   //Retryer:該組決定了在http請(qǐng)求失敗時(shí)是否需要重試
   //RequestInterceptor:請(qǐng)求前的攔截器
   //Logger:記錄日志組件,包含各個(gè)階段記錄日志的方法和留給用戶自己實(shí)現(xiàn)的log方法
   //Logger.Level:日志級(jí)別
   //decode404:處理404的策略,返回空還是報(bào)錯(cuò)
   //synchronousMethodHandlerFactory通過所有的信息去包裝一個(gè)synchronousMethodHandler,在調(diào)用invoke方法的時(shí)候執(zhí)行HTTP
   return new ReflectiveFeign(handlersByName, invocationHandlerFactory);
  }

在調(diào)用Feign.Builder的target的時(shí)候,調(diào)用了ReflectiveFeign.newInstance:

 /**
  * creates an api binding to the {@code target}. As this invokes reflection, care should be taken
  * to cache the result.
  */
 @SuppressWarnings("unchecked")
 @Override
 //接收Target參數(shù)(包含feign代理接口的類型class,名稱,http URL)
 public <T> T newInstance(Target<T> target) {
  //首先通過**ParseHandlersByName**解析出接口中包含的方法,包裝RequestTemplate,組裝成<name, MethodHandler>
  Map<String, MethodHandler> nameToHandler = targetToHandlersByName.apply(target);
  Map<Method, MethodHandler> methodToHandler = new LinkedHashMap<Method, MethodHandler>();
  //接口default方法List
  List<DefaultMethodHandler> defaultMethodHandlers = new LinkedList<DefaultMethodHandler>();

  for (Method method : target.type().getMethods()) {
   if (method.getDeclaringClass() == Object.class) {
    continue;
   } else if(Util.isDefault(method)) {
    DefaultMethodHandler handler = new DefaultMethodHandler(method);
    defaultMethodHandlers.add(handler);
    methodToHandler.put(method, handler);
   } else {
    methodToHandler.put(method, nameToHandler.get(Feign.configKey(target.type(), method)));
   }
  }
  //InvocationHandlerFactory.Default()返回了一個(gè)ReflectiveFeign.FeignInvocationHandler對(duì)象,通過傳入的methodHandler map 調(diào)用目標(biāo)對(duì)象的對(duì)應(yīng)方法
  InvocationHandler handler = factory.create(target, methodToHandler);
  //生成JDK代理對(duì)象
  T proxy = (T) Proxy.newProxyInstance(target.type().getClassLoader(), new Class<?>[]{target.type()}, handler);
  //綁定接口的默認(rèn)方法到代理對(duì)象
  for(DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) {
   defaultMethodHandler.bindTo(proxy);
  }
  return proxy;
 }

生成Feign代理對(duì)象的基本流程圖:

Spring-cloud Feign的示例分析

當(dāng)調(diào)用接口方法時(shí),實(shí)際上就是調(diào)用代理對(duì)象invoke方法:

 @Override
 public Object invoke(Object[] argv) throws Throwable {
  //工廠創(chuàng)建請(qǐng)求模版
  RequestTemplate template = buildTemplateFromArgs.create(argv);
  //每次克隆一個(gè)新的Retryer
  Retryer retryer = this.retryer.clone();
  while (true) {
   try {
    //這里調(diào)用實(shí)際的Feign client execute
    return executeAndDecode(template);
   } catch (RetryableException e) {
    //失敗重試
    retryer.continueOrPropagate(e);
    if (logLevel != Logger.Level.NONE) {
     logger.logRetry(metadata.configKey(), logLevel);
    }
    continue;
   }
  }
 }

在DefaultFeignLoadBalancedConfiguration里實(shí)例化了LoadBalancerFeignClient

  @Override
  public Response execute(Request request, Request.Options options) throws IOException {
    try {
      URI asUri = URI.create(request.url());
      String clientName = asUri.getHost();
      URI uriWithoutHost = cleanUrl(request.url(), clientName);
      //delegate這里是Client.Default實(shí)例,底層調(diào)用的是java.net原生網(wǎng)絡(luò)訪問
      FeignLoadBalancer.RibbonRequest ribbonRequest = new FeignLoadBalancer.RibbonRequest(
          this.delegate, request, uriWithoutHost);

      IClientConfig requestConfig = getClientConfig(options, clientName);
      //executeWithLoadBalancer會(huì)根據(jù)ribbon的負(fù)載均衡算法構(gòu)建url,這里不展開
      return lbClient(clientName).executeWithLoadBalancer(ribbonRequest,
          requestConfig).toResponse();
    }
    catch (ClientException e) {
      IOException io = findIOException(e);
      if (io != null) {
        throw io;
      }
      throw new RuntimeException(e);
    }
  }

感謝各位的閱讀!關(guān)于“Spring-cloud Feign的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI