這篇文章給大家分享的是有關(guān)Spring-cloud Feign的示例分析的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。
為孝昌等地區(qū)用戶(hù)提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及孝昌網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為做網(wǎng)站、網(wǎng)站制作、孝昌網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專(zhuān)業(yè)、用心的態(tài)度為用戶(hù)提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶(hù)的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
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, Mapattributes) { 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); //如果注解沒(méi)有指定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)); } protectedT loadBalance(Feign.Builder builder, FeignContext context, HardCodedTarget 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類(lèi)型:
@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作用是通過(guò)傳入的target返回代理接口下的方法的各種信息(MethodHandler) //Contract:解析接口的方法注解規(guī)則,生成MethodMetadata //Options:Request超時(shí)配置 //Encoder:請(qǐng)求編碼器 //Decoder:返回解碼器 //ErrorDecoder:錯(cuò)誤解碼器 //SynchronousMethodHandler.Factory是構(gòu)建SynchronousMethodHandler的工廠(chǎng) //Client:代表真正執(zhí)行HTTP的組件 //Retryer:該組決定了在http請(qǐng)求失敗時(shí)是否需要重試 //RequestInterceptor:請(qǐng)求前的攔截器 //Logger:記錄日志組件,包含各個(gè)階段記錄日志的方法和留給用戶(hù)自己實(shí)現(xiàn)的log方法 //Logger.Level:日志級(jí)別 //decode404:處理404的策略,返回空還是報(bào)錯(cuò) //synchronousMethodHandlerFactory通過(guò)所有的信息去包裝一個(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代理接口的類(lèi)型class,名稱(chēng),http URL) publicT newInstance(Target target) { //首先通過(guò)**ParseHandlersByName**解析出接口中包含的方法,包裝RequestTemplate,組裝成 Map nameToHandler = targetToHandlersByName.apply(target); Map methodToHandler = new LinkedHashMap (); //接口default方法List List defaultMethodHandlers = new LinkedList (); 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ì)象,通過(guò)傳入的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ì)象的基本流程圖:
當(dāng)調(diào)用接口方法時(shí),實(shí)際上就是調(diào)用代理對(duì)象invoke方法:
@Override public Object invoke(Object[] argv) throws Throwable { //工廠(chǎng)創(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ò)訪(fǎng)問(wèn) FeignLoadBalancer.RibbonRequest ribbonRequest = new FeignLoadBalancer.RibbonRequest( this.delegate, request, uriWithoutHost); IClientConfig requestConfig = getClientConfig(options, clientName); //executeWithLoadBalancer會(huì)根據(jù)ribbon的負(fù)載均衡算法構(gòu)建url,這里不展開(kāi) 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í),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!