Spring Cloud OpenFeign REST服務(wù)客戶端原理及用法解析
OpenFeign是什么?
OpenFeign是REST服務(wù)客戶端,REST其實(shí)就是HTTP啦,所以O(shè)penFeign其實(shí)就是HTTP客戶端,那么他和HttpClient有什么不同呢
OpenFeign的使用方法更加的簡單 OpenFeign配合Spring的HttpMessageConverters可以自動(dòng)把結(jié)果轉(zhuǎn)換成Java對象 OpenFeign配合Ribbon、Eureka和Spring Cloud LoadBalancer可以支持負(fù)載均衡如何使用OpenFeign
第一步引入OpenFeign
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
第二步啟動(dòng)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負(fù)載均衡(后面會(huì)詳細(xì)介紹如何做)。
在@FeignClient中還可以設(shè)置url參數(shù),它表示提供REST服務(wù)的地址,如果你沒有設(shè)置url參數(shù),那么就要在配置文件中配置。
之后我們就可以把StoreClient注入到我們需要使用的地方啦。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JavaScript實(shí)現(xiàn)多球運(yùn)動(dòng)效果2. 詳談ajax返回?cái)?shù)據(jù)成功 卻進(jìn)入error的方法3. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼4. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera5. SpringMVC+Jquery實(shí)現(xiàn)Ajax功能6. ASP.NET MVC使用異步Action的方法7. XML入門精解之結(jié)構(gòu)與語法8. ASP中if語句、select 、while循環(huán)的使用方法9. 匹配模式 - XSL教程 - 410. XML入門的常見問題(一)
