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注入到我們需要使用的地方啦。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
