Spring Cloud OpenFeign如何实现REST客户端调用原理详解?
- 内容介绍
- 文章标签
- 相关推荐
本文共计392个文字,预计阅读时间需要2分钟。
OpenFeign 是一个 RESTful 服务客户端,它简化了 HTTP 客户端的调用。REST 实际上就是 HTTP,所以 OpenFeign 实际上是一个 HTTP 客户端。那么,它与 HttpClient 有什么不同呢?
OpenFeign 的使用方法更加简单,它配合 Spring 的 HttpMessage 模块工作。
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 @EnableFeignClients public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
第三步编写REST服务接口
@FeignClient(name = "stores", url = "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注入到我们需要使用的地方啦。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。
本文共计392个文字,预计阅读时间需要2分钟。
OpenFeign 是一个 RESTful 服务客户端,它简化了 HTTP 客户端的调用。REST 实际上就是 HTTP,所以 OpenFeign 实际上是一个 HTTP 客户端。那么,它与 HttpClient 有什么不同呢?
OpenFeign 的使用方法更加简单,它配合 Spring 的 HttpMessage 模块工作。
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 @EnableFeignClients public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
第三步编写REST服务接口
@FeignClient(name = "stores", url = "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注入到我们需要使用的地方啦。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

