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. JavaScript避免嵌套代码浅析2. CSS Hack大全-教你如何区分出IE6-IE10、FireFox、Chrome、Opera3. 在 XSL/XSLT 中实现随机排序4. 《CSS3实战》笔记--渐变设计(一)5. asp(vbs)Rs.Open和Conn.Execute的详解和区别及&H0001的说明6. XML在语音合成中的应用7. CSS3实例分享之多重背景的实现(Multiple backgrounds)8. Vue Element UI 表单自定义校验规则及使用9. 用css截取字符的几种方法详解(css排版隐藏溢出文本)10. chatGPT教我写compose函数的详细过程
