這篇文章給大家分享的是有關(guān)Spring-cloud Feign的示例分析的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
為孝昌等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及孝昌網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為做網(wǎng)站、網(wǎng)站制作、孝昌網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(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) { //注冊feign配置信息 registerDefaultConfiguration(metadata, registry); //注冊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) { // 因為指定了URL且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實例 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返回了一個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超時配置 //Encoder:請求編碼器 //Decoder:返回解碼器 //ErrorDecoder:錯誤解碼器 //SynchronousMethodHandler.Factory是構(gòu)建SynchronousMethodHandler的工廠 //Client:代表真正執(zhí)行HTTP的組件 //Retryer:該組決定了在http請求失敗時是否需要重試 //RequestInterceptor:請求前的攔截器 //Logger:記錄日志組件,包含各個階段記錄日志的方法和留給用戶自己實現(xiàn)的log方法 //Logger.Level:日志級別 //decode404:處理404的策略,返回空還是報錯 //synchronousMethodHandlerFactory通過所有的信息去包裝一個synchronousMethodHandler,在調(diào)用invoke方法的時候執(zhí)行HTTP return new ReflectiveFeign(handlersByName, invocationHandlerFactory); }
在調(diào)用Feign.Builder的target的時候,調(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()返回了一個ReflectiveFeign.FeignInvocationHandler對象,通過傳入的methodHandler map 調(diào)用目標(biāo)對象的對應(yīng)方法 InvocationHandler handler = factory.create(target, methodToHandler); //生成JDK代理對象 T proxy = (T) Proxy.newProxyInstance(target.type().getClassLoader(), new Class<?>[]{target.type()}, handler); //綁定接口的默認(rèn)方法到代理對象 for(DefaultMethodHandler defaultMethodHandler : defaultMethodHandlers) { defaultMethodHandler.bindTo(proxy); } return proxy; }
生成Feign代理對象的基本流程圖:
當(dāng)調(diào)用接口方法時,實際上就是調(diào)用代理對象invoke方法:
@Override public Object invoke(Object[] argv) throws Throwable { //工廠創(chuàng)建請求模版 RequestTemplate template = buildTemplateFromArgs.create(argv); //每次克隆一個新的Retryer Retryer retryer = this.retryer.clone(); while (true) { try { //這里調(diào)用實際的Feign client execute return executeAndDecode(template); } catch (RetryableException e) { //失敗重試 retryer.continueOrPropagate(e); if (logLevel != Logger.Level.NONE) { logger.logRetry(metadata.configKey(), logLevel); } continue; } } }
在DefaultFeignLoadBalancedConfiguration里實例化了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實例,底層調(diào)用的是java.net原生網(wǎng)絡(luò)訪問 FeignLoadBalancer.RibbonRequest ribbonRequest = new FeignLoadBalancer.RibbonRequest( this.delegate, request, uriWithoutHost); IClientConfig requestConfig = getClientConfig(options, clientName); //executeWithLoadBalancer會根據(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)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
網(wǎng)站題目:Spring-cloudFeign的示例分析
標(biāo)題路徑:http://www.rwnh.cn/article10/jepjdo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機(jī)、、靜態(tài)網(wǎng)站、企業(yè)網(wǎng)站制作、品牌網(wǎng)站建設(shè)、移動網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)