介绍
Spring Cloud OpenFeign
通过自动配置来绑定到 Spring
环境中,以此实现将 OpenFeign
集成到 SpringBoot
应用中。
Feign
本身是一个声明式的 webservice 客户端。它的目的是为了简化 webservice 的编写。通过创建一个接口,并且在接口上使用相应的注解,便可以直接使用 Feign
。
Feign
提供了可插拔的注解支持,包含了JAX-RS
注解。
Feign
提供了可插拔的编码和解码功能。
Spring Cloud
在此基础上了,构建了 OpenFeign
,增加了对 Spring MVC
注解的支持和在Spring Web
中默认使用的相同HttpMessageConverters
的支持。使得 OpenFeign
可以支持 REST
风格的客户端。
当项目中使用 Spring Cloud OpenFeign
时, Spring Cloud
会自动地集成 Ribbon
和 Eureka
,来提供一个支持服务发现和具备负载均衡的 HTTP
客户端。
Eureka
:当应用使用了Eureka
作为服务发现组件时,OpenFeign
会首先前往Eureka
的注册中心中查找对应的服务。Ribbon
:这是Spring Cloud Netflix
下的客户端的负载均衡
在 Spring Cloud OpenFeign
中,核心就是 FeignClient
。FeignClient
可以一个视为向远程服务的发起调用的 HTTP
客户端。
集成 OpenFeign
1)依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2)主类
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3)FeignClient
@FeignClient("stores")
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);
}
示例中用在主类上的注解 @EnableFeignClients
,表示开启 OpenFeign
。
示例中的 stores
就是当前 FeignClient
的名称,这是由 name
属性管理的。
OpenFeign
会创建基于 Ribbon
的具备负载均衡能力的 HTTP
客户端。该客户端会通过之前指定的名称,去查找服务对应的物理地址。如果应用中使用了 Eureka
作为服务发现组件,那么将会去 Eureka
的注册中心找到相匹配的服务。如果应用中未使用 Eureka
,也可以通过单独配置服务路径信息,来实现服务的查找。
在示例中 StoreClient
客户端只是一个接口,不会有实现类。Spring Cloud
会针对使用了 @FeignClient
注解的接口,创建以该接口的全限定名称作为对应Bean
的名称。 这样就可以直接通过 @Autowired
来将 StoreClient
接口注入到其他类中。
Feign默认配置
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic
hello-service:
connectTimeout: 3000
readTimeout: 3000
loggerLevel: basic
default
:作用域为所有的@FeignClient
hello-service
:指定的FeignClient
connectTimeout
:连接超时时间(毫秒)readTimeout
:业务执行超时时间(毫秒)loggerLevel
: 日志级别
Demo
1. Eureka-Server
1.1. 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId