Spring Cloud OpenFeign REST服務(wù)客戶端原理及用法解析
OpenFeign是什么?
OpenFeign是REST服務(wù)客戶端,REST其實就是HTTP啦,所以O(shè)penFeign其實就是HTTP客戶端,那么他和HttpClient有什么不同呢
OpenFeign的使用方法更加的簡單 OpenFeign配合Spring的HttpMessageConverters可以自動把結(jié)果轉(zhuǎn)換成Java對象 OpenFeign配合Ribbon、Eureka和Spring Cloud LoadBalancer可以支持負載均衡如何使用OpenFeign
第一步引入OpenFeign
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
第二步啟動OpenFeign客戶端功能
@SpringBootApplication@EnableFeignClientspublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
第三步編寫REST服務(wù)接口
@FeignClient(name = 'stores', url = 'http://localhost:7074')<br data-filtered='filtered'>public interface StoreClient { @RequestMapping(method = RequestMethod.GET, value = '/stores') List<Store> getStores(); @RequestMapping(method = RequestMethod.POST, value = '/stores/{storeId}', consumes = 'application/json') Store update(@PathVariable('storeId') Long storeId, Store store);}
在@FeignClient中的字符串稱為Feign客戶端名字,它可以是任意的字符串,設(shè)置名字的目的就是為了方便在其它地方引用它,例如配置Rabbin或Spring Cloud LoadBalancer負載均衡(后面會詳細介紹如何做)。
在@FeignClient中還可以設(shè)置url參數(shù),它表示提供REST服務(wù)的地址,如果你沒有設(shè)置url參數(shù),那么就要在配置文件中配置。
之后我們就可以把StoreClient注入到我們需要使用的地方啦。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Spring security 自定義過濾器實現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實例代碼)2. Java8內(nèi)存模型PermGen Metaspace實例解析3. 多級聯(lián)動下拉選擇框,動態(tài)獲取下一級4. ASP.NET MVC使用正則表達式驗證手機號碼5. Python 中random 庫的詳細使用6. Spring注入Date類型的三種方法總結(jié)7. ASP新手必備的基礎(chǔ)知識8. XML和JSP的聯(lián)手9. Python基于百度AI實現(xiàn)抓取表情包10. Python使用sftp實現(xiàn)上傳和下載功能
