Spring Cloud OpenFeign REST服務客戶端原理及用法解析
OpenFeign是什么?
OpenFeign是REST服務客戶端,REST其實就是HTTP啦,所以OpenFeign其實就是HTTP客戶端,那么他和HttpClient有什么不同呢
OpenFeign的使用方法更加的簡單 OpenFeign配合Spring的HttpMessageConverters可以自動把結果轉換成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服務接口
@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客戶端名字,它可以是任意的字符串,設置名字的目的就是為了方便在其它地方引用它,例如配置Rabbin或Spring Cloud LoadBalancer負載均衡(后面會詳細介紹如何做)。
在@FeignClient中還可以設置url參數,它表示提供REST服務的地址,如果你沒有設置url參數,那么就要在配置文件中配置。
之后我們就可以把StoreClient注入到我們需要使用的地方啦。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. Python使用oslo.vmware管理ESXI虛擬機的示例參考2. Jsp servlet驗證碼工具類分享3. .NET6打包部署到Windows Service的全過程4. python GUI庫圖形界面開發之PyQt5滑塊條控件QSlider詳細使用方法與實例5. JetBrains IntelliJ IDEA 配置優化技巧6. idea2020.1無法自動加載maven依賴的jar包問題及解決方法7. Intellij idea熱部署插件JRebel的使用8. PHP程序員簡單的開展服務治理架構操作詳解(一)9. 解決idea update project 更新選項消失的問題10. IntelliJ IDEA 好用插件之analyze inspect code詳解
