亚洲精品中文免费|亚洲日韩中文字幕制服|久久精品亚洲免费|一本之道久久免费

      
      

            <dl id="hur0q"><div id="hur0q"></div></dl>

                「Feign」OpenFeign入門以及遠(yuǎn)程調(diào)用

                一、OpenFeign介紹

                OpenFeign是 種聲明式,模版化的HTTP客戶端。使 OpenFeign進(jìn) 遠(yuǎn)程調(diào) 時(shí),開發(fā)者完全感知不到這是在進(jìn) 遠(yuǎn)程調(diào) , 是像在調(diào) 本地 法 樣。使 式是注解+接 形式,把需要調(diào) 的遠(yuǎn)程接 封裝到接 當(dāng)中,映射地址為遠(yuǎn)程接 的地址。在啟動(dòng)SpringCloud應(yīng) 時(shí),F(xiàn)eign會(huì)掃描標(biāo)有@FeignClient注解的接 , 成代理并且注冊(cè)到Spring容器當(dāng)中。 成代理時(shí)Feign會(huì)為每個(gè)接 法創(chuàng)建 個(gè)RequestTemplate對(duì)象,該對(duì)象封裝HTTP請(qǐng)求需要的全部信息,請(qǐng)求參數(shù)名、請(qǐng)求 法等信息都是在這個(gè)過程中確定的,模版化就體現(xiàn)在這 。

                二、OpenFeign的使用

                • 搭建前置環(huán)境,在pom.xml文件中引入依賴,可以選擇使用注冊(cè)中心或者配置中心

                org.springframework.cloud spring-cloud-dependencies 2020.0.3 pom import org.springframework.cloud spring-cloud-starter-consul-config org.springframework.cloud spring-cloud-starter-consul-discovery org.springframework.boot spring-boot-starter-actuator org.springframework.cloud spring-cloud-starter-openfeign

                1.使用注冊(cè)中心

                • 使 注冊(cè)中 ,將服務(wù)注冊(cè)到consul(nacos),調(diào) 者拿到被調(diào) 服務(wù)的地址端 進(jìn) 調(diào)

                spring.cloud.consul.host=192.168.0.124#consul地址spring.cloud.consul.port=8080#端 號(hào)spring.cloud.consul.discovery.service-name=service-test-01#服務(wù)名稱spring.cloud.consul.discovery.health-check-interval=1m#健康檢查間隔時(shí)間server.port=10000#服務(wù)端 號(hào)

                • 在配置類上開啟服務(wù)發(fā)現(xiàn)以及允許遠(yuǎn)程調(diào)

                @EnableDiscoveryClient //開啟服務(wù)發(fā)現(xiàn)@EnableFeignClients //開啟服務(wù)調(diào) ,只需要在調(diào) 開啟即可

                • 服務(wù)運(yùn) 之后可以在consul的UI界 看到運(yùn) 的服務(wù),consul會(huì)定時(shí)檢查服務(wù)的健康狀態(tài)
                • 創(chuàng)建遠(yuǎn)程調(diào)用接口

                @FeignClient(“serviceName”)public interface Service2Remote { /** 這 有 定義解碼器對(duì)遠(yuǎn)程調(diào) 的結(jié)果進(jìn) 解析,拿到真正的返回類型,所以接 返回值類型和遠(yuǎn)程接 返回類型保持 致 **/ @PostMapping(“/page”) List pageQuestion(PageQuestionReq req);}

                • 簡單使用

                @RestController@RequestMapping(“/service/remote”)public class RemoteController { @Autowired private Service2Remote service2Remote; @PostMapping(“/getQuestionList”) public List getQuestionList(@RequestBody PageQuestionReq req){ List result = service2Remote.pageQuestion(req); //對(duì)拿到的數(shù)據(jù)進(jìn) 處理… return result; }}

                2.使用配置中心

                • 將請(qǐng)求的URL寫在配置中 進(jìn) 讀取修改配置 件

                spring.cloud.consul.config.format=KEY_VALUE#consul 持yaml格式和Key-value形式spring.cloud.consul.config.enabled=true#開啟配置spring.cloud.consul.config.prefixes=glab/plat/wt/application/test#consul配置存放的外層 件夾 錄spring.cloud.consul.config.default-context=config# 級(jí) 件夾spring.cloud.consul.config.watch.delay=1000#輪詢時(shí)間spring.cloud.consul.discovery.enabled=false#關(guān)閉注冊(cè)remote.url=www.baidu.com#請(qǐng)求地址

                • 創(chuàng)建遠(yuǎn)程調(diào)用接口

                @FeignClient(name = “service2RemoteByUrl”,url = “${remote.url}”) //name需要配置,URL從配置中 讀取public interface Service2RemoteByUrl { @PostMapping(“/page”) List pageQuestion(PageQuestionReq req);}

                3.自定義解碼器(編碼器

                // 定義解碼器實(shí)現(xiàn)Decoder接 ,重寫decode 法即可,根據(jù)具體需求進(jìn) 編寫//如果是 定義編碼器,需要實(shí)現(xiàn)Encoder接 ,重寫encode 法public class FeignDecoder implements Decoder { @Override public Object decode(Response response, Type type) throws IOException,DecodeException, FeignException { if (response.body() == null){ throw new DecodeException(ErrorEnum.EXECUTE_ERR.getErrno(),”沒有獲取到有效結(jié)果值”,response.request()); } // 拿到值 String result = Util.toString(response.body().asReader(Util.UTF_8)); Map resMap = null; try { resMap = JSON.parseObject(result, Map.class); } catch (Exception e) { //返回結(jié)果是字符串 return result; }}

                4.遠(yuǎn)程調(diào)用攜帶Cookie

                • 由于feign調(diào) 是新創(chuàng)建 個(gè)Request,因此在請(qǐng)求時(shí)不會(huì)攜帶 些原本就有的信息,例如Cookie,因此需要 定義RequestInterceptor對(duì)Request進(jìn) 額外設(shè)置, 般情況下,寫 Cookie是 較常 的做法,如下設(shè)置

                @Configurationpublic class BeanConfig { @Bean public RequestInterceptor requestInterceptor(){ return template -> { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //此處可以根據(jù)業(yè)務(wù) 具體定制攜帶規(guī)則 String data = request.getParameter(“data”); String code = null; try { //這 需要轉(zhuǎn)碼,否則會(huì)報(bào)錯(cuò) code = URLEncoder.encode(data, “UTF-8”); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } template.query(“data”,code); //請(qǐng)求頭中攜帶Cookie String cookie = request.getHeader(“Cookie”); template.header(“Cookie”,cookie); }; } @Bean public Decoder decoder(){ return new FeignDecoder(); }}

                三、調(diào)用流程解析

                //在使 EnableFeignClients開啟feign功能時(shí),點(diǎn)擊進(jìn) 會(huì)看到該注解是通過ImportFeignClientsRegistrar類 效的,其中有個(gè) 法//registerBeanDefinitions執(zhí) 兩條語句registerDefaultConfiguration(metadata, registry); //加載默認(rèn)配置信息registerFeignClients(metadata, registry); //注冊(cè)掃描標(biāo)有FeignClient的接 //關(guān)注registerFeignClients 法for (String basePackage : basePackages) { candidateComponents.addAll(scanner.findCandidateComponents(basePackage)); //在basePackage路徑下掃描并添加標(biāo)有FeignClient的接 }for (BeanDefinition candidateComponent : candidateComponents) { //遍歷 if (candidateComponent instanceof AnnotatedBeanDefinition) { registerClientConfiguration(registry, name, attributes.get(“configuration”)); // registerFeignClient(registry, annotationMetadata, attributes); //注冊(cè)到Spring容器當(dāng)中, 法詳細(xì)在FeignClientsRegistrar類當(dāng)中 }}//在對(duì)feign調(diào) 時(shí)進(jìn) 斷點(diǎn)調(diào)試//在 成Feign遠(yuǎn)程接 的代理類時(shí),調(diào) 處理器是Feign提供的FeignInvocationHandlerpublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (“equals”.equals(method.getName())) { //equals,hashCode,toString三個(gè) 法直接本地執(zhí) } else if (“hashCode”.equals(method.getName())) { return hashCode(); } else if (“toString”.equals(method.getName())) { return toString(); } //執(zhí) 法對(duì)應(yīng)的 法處理器MethodHandler,這個(gè)接 是Feign提供的,與InvocationHandler 任何關(guān)系,只有 個(gè)invoke 法 return dispatch.get(method).invoke(args);}//點(diǎn)進(jìn)上 的invoke 法public Object invoke(Object[] argv) throws Throwable { //創(chuàng)建 個(gè)request模版 RequestTemplate template = buildTemplateFromArgs.create(argv); while (true) { try { return executeAndDecode(template, options); //創(chuàng)建request執(zhí) 并且解碼 } }}Object executeAndDecode(RequestTemplate template, Options options) throws Throwable { Request request = targetRequest(template); //創(chuàng)建Request并增強(qiáng) Response response = client.execute(request, options); //執(zhí) 調(diào)用請(qǐng)求,不再繼續(xù)分析了 response = response.toBuilder().request(request).requestTemplate(template).build(); //如果有重寫解碼器,使 定義的解碼器,feign默認(rèn)使 SpringEncoder if (decoder != null) return decoder.decode(response, metadata.returnType()); } Request targetRequest(RequestTemplate template) { //如果 定義了RequestInterceptor,在這 可以對(duì)Request進(jìn) 增強(qiáng) for (RequestInterceptor interceptor : requestInterceptors) { //執(zhí) 定義的apply 法 interceptor.apply(template); } //創(chuàng)建Request return target.apply(template);}

                四、補(bǔ)充

                • 關(guān)于Client接 的實(shí)現(xiàn)類,使 注冊(cè)中 和使 配置中 其流程稍有區(qū)別

                //使 配置中 拿url 式進(jìn) 調(diào) ,使 的是Client的默認(rèn)內(nèi)部實(shí)現(xiàn)類 Default ,其中Default使 的是HttpURLConnection進(jìn) Http請(qǐng)求的HttpURLConnection connection = convertAndSend(request, options);//如果使 的是服務(wù)發(fā)現(xiàn),使 的使 Client的實(shí)現(xiàn)類FeignBlockingLoadBalancerClient,它會(huì)去根據(jù)配置的服務(wù)名去注冊(cè)中 查找服務(wù)的IP地址和端 號(hào),執(zhí) 使 的仍然是默認(rèn)實(shí)現(xiàn)類Default,通過HttpURLConnection請(qǐng)求//FeignBlockingLoadBalancerClient,根據(jù)服務(wù)名稱查找服務(wù)IP地址、端 88 ServiceInstance instance = loadBalancerClient.choose(serviceId, lbRequest);//具體實(shí)現(xiàn) 法,BlockingLoadBalancerClient類中 145 Response loadBalancerResponse = Mono.from(loadBalancer.choose(request)).block();//還有其他實(shí)現(xiàn)Client接 的客戶端,例如ApacheHttpClient,ApacheHttpClient帶有連接池功能,具有優(yōu)秀的HTTP連接復(fù) 能 ,需要通過引 依賴來使

                鄭重聲明:本文內(nèi)容及圖片均整理自互聯(lián)網(wǎng),不代表本站立場,版權(quán)歸原作者所有,如有侵權(quán)請(qǐng)聯(lián)系管理員(admin#wlmqw.com)刪除。
                用戶投稿
                上一篇 2022年6月13日 21:14
                下一篇 2022年6月13日 21:14

                相關(guān)推薦

                • 計(jì)算機(jī)網(wǎng)絡(luò)技術(shù)論文(計(jì)算機(jī)網(wǎng)絡(luò)技術(shù)論文七千字)

                  今天小編給各位分享計(jì)算機(jī)網(wǎng)絡(luò)技術(shù)論文的知識(shí),其中也會(huì)對(duì)計(jì)算機(jī)網(wǎng)絡(luò)技術(shù)論文七千字進(jìn)行解釋,如果能碰巧解決你現(xiàn)在面臨的問題,別忘了關(guān)注本站,現(xiàn)在開始吧! 計(jì)算機(jī)網(wǎng)絡(luò)方面的論文3000字…

                  2022年11月26日
                • 抖音帶貨怎么做入門(抖音帶貨怎么做入門教學(xué))

                  相信很多小伙伴都有注意到,現(xiàn)在抖音已經(jīng)成為大家最常光顧的一個(gè)平臺(tái)了,作為一個(gè)日活破億的流量池,如今抖音上的用戶數(shù)量極大。因此,現(xiàn)在在抖音上帶貨、賣貨的人也是越來越多了,那么想在抖音…

                  2022年11月25日
                • 沈陽茂業(yè)中心

                  由深圳贏商網(wǎng)茂業(yè)集團(tuán)與上海建工集團(tuán)聯(lián)袂打造的沈陽金廊第一高樓沈陽茂業(yè)中心于2011年11月8日順利實(shí)現(xiàn)主塔樓結(jié)構(gòu)封頂至此,歷經(jīng)四年,沈陽茂業(yè)中心以31095m的高度雄踞東北超高層建…

                  2022年11月25日
                • 前三季度,市場規(guī)模超過五萬億元 信息消費(fèi)展現(xiàn)蓬勃生機(jī)

                  家居企業(yè)個(gè)性化全屋定制系統(tǒng),備受消費(fèi)者青睞;主打?qū)I(yè)電競的新款高性能便攜式計(jì)算機(jī),銷量表現(xiàn)創(chuàng)新高;物流企業(yè)推出數(shù)智化供應(yīng)鏈興農(nóng)服務(wù)項(xiàng)目,助力優(yōu)質(zhì)農(nóng)產(chǎn)品出深山…… 不久前,工信部發(fā)布…

                  2022年11月24日
                • 1千克等于多少磅

                  克,此定義在1958年被美國以及其他英聯(lián)邦會(huì)員國承認(rèn)換算回來,一千克等于262磅,一磅等于037千克英國在1963年開始,依據(jù)度量衡法案的規(guī);1 磅=16 盎司=04536 千克 …

                  2022年11月24日
                • 廣州花都嶺南批發(fā)地女裝在哪拿貨好(廣州花都嶺南批發(fā)地女裝)

                  廣州的服裝批發(fā)市場人氣一直也都挺高的,不過很多商家第一次來廣州進(jìn)貨,對(duì)于一些女裝貨源批發(fā)還不是很了解。廣州花都嶺南批發(fā)地女裝在哪拿貨好?現(xiàn)在廣州服裝貨源批發(fā)哪里最便宜呢?今天小編整…

                  2022年11月23日
                • 微信健康碼怎么注銷重新申請(qǐng)健康碼 怎么更換綁定人

                  在疫情常態(tài)化的管理之下,出行都需要健康碼,那么如果因?yàn)榉N種原因注銷了健康碼怎么辦呢?這種情況下是否還可以再申請(qǐng)健康碼呢?下面一起來看看了解一下吧! 微信健康碼注銷了還能申請(qǐng)嗎 健康…

                  2022年11月22日
                • 拼多多免費(fèi)領(lǐng)商品有什么規(guī)則(拼多多免費(fèi)領(lǐng)商品金幣后面是什么)

                  拼多多免費(fèi)領(lǐng)商品活動(dòng)相信不少小伙伴都參加過,吸引力還是很大的,只要砍價(jià)成功就可以免費(fèi)領(lǐng)到商品,一些小伙伴第一次參加不知道拼多多免費(fèi)領(lǐng)商品有什么規(guī)則?下面小編為大家?guī)砥炊喽嗝赓M(fèi)領(lǐng)商…

                  2022年11月21日
                • 個(gè)人核心能力有哪些一個(gè)人想要成長,需要具備這5項(xiàng)核心能力

                  能力。Enjoy~ 01 培養(yǎng)成長型心態(tài) 斯坦福大學(xué)心理學(xué)教授卡羅爾·德維克在做“如何應(yīng)對(duì)失敗”的研究時(shí),曾做過一個(gè)試驗(yàn):她給一群小學(xué)生一些特別難的字謎,然后觀察他們的反應(yīng)。 她發(fā)…

                  2022年11月20日
                • 京東店鋪類型有哪些京東入駐有什么資質(zhì)要求

                  今天的互聯(lián)網(wǎng)發(fā)展迅速,讓傳統(tǒng)企業(yè)有了更多選擇,但也同樣也對(duì)剛觸網(wǎng)的商家增添了許多迷茫,近日知舟電商就收到很多商家朋友詢問京東入駐相關(guān)問題,今天知舟君就給大家分享下。 一.京東入駐準(zhǔn)…

                  2022年11月18日

                聯(lián)系我們

                聯(lián)系郵箱:admin#wlmqw.com
                工作時(shí)間:周一至周五,10:30-18:30,節(jié)假日休息