4.0.6
此项目通过自动配置和绑定到 Spring 环境以及其他 Spring 编程模型习惯用法,为 Spring Boot 应用程序提供 OpenFeign 集成。
1. 声明式 REST 客户端:Feign
Feign 是一个声明式 Web 服务客户端。它使编写 Web 服务客户端更加容易。要使用 Feign,请创建一个接口并对其进行注释。它具有可插拔的注释支持,包括 Feign 注释和 JAX-RS 注释。Feign 还支持可插拔的编码器和解码器。Spring Cloud 添加了对 Spring MVC 注释的支持,以及使用 Spring Web 中默认使用的相同 HttpMessageConverters
。Spring Cloud 集成了 Eureka、Spring Cloud CircuitBreaker 以及 Spring Cloud LoadBalancer,在使用 Feign 时提供负载均衡的 http 客户端。
1.1. 如何包含 Feign
要在项目中包含 Feign,请使用 group 为 org.springframework.cloud
,artifact id 为 spring-cloud-starter-openfeign
的启动器。有关使用当前 Spring Cloud 版本列车设置构建系统的详细信息,请参阅 Spring Cloud 项目页面。
示例 spring boot 应用
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@FeignClient("stores")
public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores")
List<Store> getStores();
@RequestMapping(method = RequestMethod.GET, value = "/stores")
Page<Store> getStores(Pageable pageable);
@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
Store update(@PathVariable("storeId") Long storeId, Store store);
@RequestMapping(method = RequestMethod.DELETE, value = "/stores/{storeId:\\d+}")
void delete(@PathVariable Long storeId);
}
在 @FeignClient
注释中,字符串值(上面的“stores”)是一个任意的客户端名称,用于创建 Spring Cloud LoadBalancer 客户端。您还可以使用 url
属性指定 URL(绝对值或仅主机名)。应用程序上下文中的 bean 名称是接口的全限定名称。要指定您自己的别名值,可以使用 @FeignClient
注释的 qualifiers
值。
上面的负载均衡器客户端将需要发现“stores”服务的物理地址。如果您的应用程序是 Eureka 客户端,它将在 Eureka 服务注册表中解析该服务。如果您不想使用 Eureka,您可以使用 SimpleDiscoveryClient
在外部配置中配置服务器列表。
Spring Cloud OpenFeign 支持 Spring Cloud LoadBalancer 块模式下提供的所有功能。您可以在 项目文档 中阅读更多相关信息。
要在 @Configuration 注释的类上使用 @EnableFeignClients 注释,请确保指定客户端的位置,例如:@EnableFeignClients(basePackages = "com.example.clients") 或显式列出它们:@EnableFeignClients(clients = InventoryServiceFeignClient.class) |
1.1.1. 属性解析模式
在创建 Feign
客户端 bean 时,我们解析通过 @FeignClient
注释传递的值。从 4.x
开始,这些值将被急切地解析。对于大多数用例来说,这是一个很好的解决方案,它也允许 AOT 支持。
如果您需要延迟解析属性,请将 spring.cloud.openfeign.lazy-attributes-resolution
属性值设置为 true
。
对于 Spring Cloud Contract 测试集成,应使用延迟属性解析。 |
1.2. 覆盖 Feign 默认值
Spring Cloud 中 Feign 支持的核心概念是命名客户端。每个 feign 客户端都是组件集合的一部分,这些组件协同工作以按需联系远程服务器,并且该集合具有您作为应用程序开发人员使用 @FeignClient
注释赋予它的名称。Spring Cloud 使用 FeignClientsConfiguration
按需为每个命名客户端创建一个新的集合作为 ApplicationContext
。这包含(除其他外)feign.Decoder
、feign.Encoder
和 feign.Contract
。可以使用 @FeignClient
注释的 contextId
属性覆盖该集合的名称。
Spring Cloud 允许您通过使用 @FeignClient
声明额外的配置(在 FeignClientsConfiguration
之上)来完全控制 feign 客户端。示例
@FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient {
//..
}
在这种情况下,客户端由 FeignClientsConfiguration
中的组件以及 FooConfiguration
中的任何组件组成(后者将覆盖前者)。
FooConfiguration 不需要用 @Configuration 注释。但是,如果是这样,请注意将其从任何 @ComponentScan 中排除,否则该组件将包含此配置,因为它将成为 feign.Decoder 、feign.Encoder 、feign.Contract 等的默认来源。这可以通过将其放在与任何 @ComponentScan 或 @SpringBootApplication 不重叠的单独包中来避免,或者可以在 @ComponentScan 中显式排除它。 |
除了更改 ApplicationContext 集合的名称外,使用 @FeignClient 注释的 contextId 属性还可以覆盖客户端名称的别名,并且它将用作为此客户端创建的配置 bean 名称的一部分。 |
以前,使用 url 属性不需要 name 属性。现在需要使用 name 。 |
name
和 url
属性支持占位符。
@FeignClient(name = "${feign.name}", url = "${feign.url}")
public interface StoreClient {
//..
}
Spring Cloud OpenFeign 默认情况下为 feign 提供以下 bean(BeanType
beanName:ClassName
)
-
Decoder
feignDecoder:ResponseEntityDecoder
(它包装了SpringDecoder
) -
Encoder
feignEncoder:SpringEncoder
-
Logger
feignLogger:Slf4jLogger
-
MicrometerObservationCapability
micrometerObservationCapability:如果feign-micrometer
位于类路径上并且ObservationRegistry
可用 -
MicrometerCapability
micrometerCapability:如果feign-micrometer
位于类路径上,MeterRegistry
可用且ObservationRegistry
不可用 -
CachingCapability
cachingCapability:如果使用@EnableCaching
注释。可以通过spring.cloud.openfeign.cache.enabled
禁用。 -
Contract
feignContract:SpringMvcContract
-
Feign.Builder
feignBuilder:FeignCircuitBreaker.Builder
-
Client
feignClient:如果 Spring Cloud LoadBalancer 位于类路径上,则使用FeignBlockingLoadBalancerClient
。如果它们都不在类路径上,则使用默认的 feign 客户端。
spring-cloud-starter-openfeign 支持 spring-cloud-starter-loadbalancer 。但是,这是一个可选依赖项,如果您想使用它,则需要确保已将其添加到您的项目中。 |
要使用 OkHttpClient 支持的 Feign 客户端,请确保 OKHttpClient 位于您的类路径上并将 spring.cloud.openfeign.okhttp.enabled
设置为 true
。
对于 Apache HttpClient 5 支持的 Feign 客户端,只需确保 HttpClient 5 位于类路径上即可,但您仍然可以通过将 spring.cloud.openfeign.httpclient.hc5.enabled
设置为 false
来禁用它在 Feign 客户端中的使用。您可以通过提供 org.apache.hc.client5.http.impl.classic.CloseableHttpClient
的 bean 来自定义使用的 HTTP 客户端(当使用 Apache HC5 时)。
您可以通过设置 spring.cloud.openfeign.httpclient.xxx
属性中的值来进一步自定义 http 客户端。仅以 httpclient
为前缀的那些将适用于所有客户端,以 httpclient.hc5
为前缀的那些适用于 Apache HttpClient 5,而以 httpclient.okhttp
为前缀的那些适用于 OkHttpClient。您可以在附录中找到可以自定义的属性的完整列表。
从 Spring Cloud OpenFeign 4 开始,Feign Apache HttpClient 4 不再受支持。我们建议改用 Apache HttpClient 5。 |
Spring Cloud OpenFeign *不*默认情况下为 feign 提供以下 bean,但仍然会从应用程序上下文中查找这些类型的 bean 以创建 feign 客户端
-
Logger.Level
-
Retryer
-
ErrorDecoder
-
Request.Options
-
Collection<RequestInterceptor>
-
SetterFactory
-
QueryMapEncoder
-
Capability
(MicrometerObservationCapability
和CachingCapability
默认提供)
默认情况下会创建一个类型为 Retryer
的 Retryer.NEVER_RETRY
bean,这将禁用重试。请注意,此重试行为与 Feign 默认行为不同,Feign 默认行为会自动重试 IOException,将其视为瞬态网络相关异常,以及从 ErrorDecoder 抛出的任何 RetryableException。
创建这些类型之一的 bean 并将其放在 @FeignClient
配置(例如上面的 FooConfiguration
)中,允许您覆盖每个描述的 bean。示例
@Configuration
public class FooConfiguration {
@Bean
public Contract feignContract() {
return new feign.Contract.Default();
}
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "password");
}
}
这将 SpringMvcContract
替换为 feign.Contract.Default
并向 RequestInterceptor
集合添加 RequestInterceptor
。
@FeignClient
也可以使用配置属性进行配置。
application.yml
spring:
cloud:
openfeign:
client:
config:
feignName:
url: http://remote-service.com
connectTimeout: 5000
readTimeout: 5000
loggerLevel: full
errorDecoder: com.example.SimpleErrorDecoder
retryer: com.example.SimpleRetryer
defaultQueryParameters:
query: queryValue
defaultRequestHeaders:
header: headerValue
requestInterceptors:
- com.example.FooRequestInterceptor
- com.example.BarRequestInterceptor
responseInterceptor: com.example.BazResponseInterceptor
dismiss404: false
encoder: com.example.SimpleEncoder
decoder: com.example.SimpleDecoder
contract: com.example.SimpleContract
capabilities:
- com.example.FooCapability
- com.example.BarCapability
queryMapEncoder: com.example.SimpleQueryMapEncoder
micrometer.enabled: false
此示例中的 feignName
指的是 @FeignClient
value
,该值也与 @FeignClient
name
和 @FeignClient
contextId
具有别名。在负载均衡方案中,它还对应于将用于检索实例的服务器应用程序的 serviceId
。解码器、重试器和其他指定类的必须在 Spring 上下文中具有 bean 或具有默认构造函数。
默认配置可以在 @EnableFeignClients
属性 defaultConfiguration
中以与上述类似的方式指定。不同之处在于此配置将应用于*所有* feign 客户端。
如果您更喜欢使用配置属性来配置所有 @FeignClient
,您可以创建具有 default
feign 名称的配置属性。
您可以使用 spring.cloud.openfeign.client.config.feignName.defaultQueryParameters
和 spring.cloud.openfeign.client.config.feignName.defaultRequestHeaders
来指定将与名为 feignName
的客户端的每个请求一起发送的查询参数和标头。
application.yml
spring:
cloud:
openfeign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic
如果同时创建了@Configuration
bean和配置属性,则配置属性将优先。它会覆盖@Configuration
的值。但是,如果要将优先级更改为@Configuration
,可以将spring.cloud.openfeign.client.default-to-properties
更改为false
。
如果要创建多个具有相同名称或URL的Feign客户端,以便它们指向同一服务器但每个客户端都有不同的自定义配置,则必须使用@FeignClient
的contextId
属性来避免这些配置bean的名称冲突。
@FeignClient(contextId = "fooClient", name = "stores", configuration = FooConfiguration.class)
public interface FooClient {
//..
}
@FeignClient(contextId = "barClient", name = "stores", configuration = BarConfiguration.class)
public interface BarClient {
//..
}
还可以配置FeignClient不继承父上下文中的bean。可以通过在FeignClientConfigurer
bean中重写inheritParentConfiguration()
并返回false
来实现。
@Configuration
public class CustomConfiguration {
@Bean
public FeignClientConfigurer feignClientConfigurer() {
return new FeignClientConfigurer() {
@Override
public boolean inheritParentConfiguration() {
return false;
}
};
}
}
默认情况下,Feign客户端不会编码斜杠/ 字符。可以通过将spring.cloud.openfeign.client.decodeSlash 的值设置为false 来更改此行为。 |
1.2.1. SpringEncoder
配置
在我们提供的SpringEncoder
中,我们为二进制内容类型设置了null
字符集,为所有其他内容类型设置了UTF-8
。
可以通过将spring.cloud.openfeign.encoder.charset-from-content-type
的值设置为true
来修改此行为,以便从Content-Type
标头的字符集派生字符集。
1.3. 超时处理
我们可以为默认客户端和命名客户端配置超时。OpenFeign 使用两个超时参数
-
connectTimeout
防止由于服务器处理时间过长而阻塞调用方。 -
readTimeout
从连接建立时开始应用,当返回响应花费的时间过长时触发。
如果服务器未运行或不可用,数据包将导致连接被拒绝。通信以错误消息或回退结束。如果connectTimeout 设置得很低,这可能会在connectTimeout 之前发生。执行查找和接收此类数据包所需的时间构成了此延迟的很大一部分。它会根据涉及 DNS 查找的远程主机而发生变化。 |
1.4. 手动创建Feign客户端
在某些情况下,可能需要以使用上述方法无法实现的方式自定义Feign客户端。在这种情况下,可以使用Feign Builder API创建客户端。下面是一个示例,它创建了两个具有相同接口的Feign客户端,但每个客户端都配置了单独的请求拦截器。
@Import(FeignClientsConfiguration.class)
class FooController {
private FooClient fooClient;
private FooClient adminClient;
@Autowired
public FooController(Client client, Encoder encoder, Decoder decoder, Contract contract, MicrometerObservationCapability micrometerObservationCapability) {
this.fooClient = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.addCapability(micrometerObservationCapability)
.requestInterceptor(new BasicAuthRequestInterceptor("user", "user"))
.target(FooClient.class, "https://PROD-SVC");
this.adminClient = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.addCapability(micrometerObservationCapability)
.requestInterceptor(new BasicAuthRequestInterceptor("admin", "admin"))
.target(FooClient.class, "https://PROD-SVC");
}
}
在上面的示例中,FeignClientsConfiguration.class 是Spring Cloud OpenFeign提供的默认配置。 |
PROD-SVC 是客户端将向其发出请求的服务的名称。 |
Feign Contract 对象定义了哪些注释和值在接口上有效。自动注入的Contract bean支持SpringMVC注释,而不是默认的Feign原生注释。 |
您也可以使用Builder
配置FeignClient不继承父上下文中的bean。可以通过在Builder
上调用inheritParentContext(false)
来实现。
1.5. Feign Spring Cloud断路器支持
如果Spring Cloud断路器位于类路径上并且spring.cloud.openfeign.circuitbreaker.enabled=true
,则Feign将使用断路器包装所有方法。
要禁用每个客户端的Spring Cloud断路器支持,请使用“prototype”作用域创建一个普通的Feign.Builder
,例如:
@Configuration
public class FooConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
}
断路器名称遵循此模式<feignClientClassName>#<calledMethod>(<parameterTypes>)
。当调用具有FooClient
接口的@FeignClient
以及没有参数的调用的接口方法为bar
时,断路器名称将为FooClient#bar()
。
从2020.0.2版本开始,断路器名称模式已从<feignClientName>_<calledMethod> 更改。使用2020.0.4中引入的CircuitBreakerNameResolver ,断路器名称可以保留旧模式。 |
提供CircuitBreakerNameResolver
的bean,可以更改断路器名称模式。
@Configuration
public class FooConfiguration {
@Bean
public CircuitBreakerNameResolver circuitBreakerNameResolver() {
return (String feignClientName, Target<?> target, Method method) -> feignClientName + "_" + method.getName();
}
}
要启用Spring Cloud断路器组,请将spring.cloud.openfeign.circuitbreaker.group.enabled
属性设置为true
(默认为false
)。
1.6. 使用配置属性配置断路器
可以通过配置属性配置断路器。
例如,如果您有此Feign客户端
@FeignClient(url = "http://localhost:8080")
public interface DemoClient {
@GetMapping("demo")
String getDemo();
}
可以通过执行以下操作使用配置属性对其进行配置
spring:
cloud:
openfeign:
circuitbreaker:
enabled: true
alphanumeric-ids:
enabled: true
resilience4j:
circuitbreaker:
instances:
DemoClientgetDemo:
minimumNumberOfCalls: 69
timelimiter:
instances:
DemoClientgetDemo:
timeoutDuration: 10s
如果要切换回Spring Cloud 2022.0.0之前使用的断路器名称,可以将spring.cloud.openfeign.circuitbreaker.alphanumeric-ids.enabled 设置为false 。 |
1.7. Feign Spring Cloud断路器回退
Spring Cloud断路器支持回退的概念:当断路器打开或出现错误时执行的默认代码路径。要为给定的@FeignClient
启用回退,请将fallback
属性设置为实现回退的类的名称。您还需要将您的实现声明为Spring bean。
@FeignClient(name = "test", url = "http://localhost:${server.port}/", fallback = Fallback.class)
protected interface TestClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
@RequestMapping(method = RequestMethod.GET, value = "/hellonotfound")
String getException();
}
@Component
static class Fallback implements TestClient {
@Override
public Hello getHello() {
throw new NoFallbackAvailableException("Boom!", new RuntimeException());
}
@Override
public String getException() {
return "Fixed response";
}
}
如果需要访问导致回退触发的根本原因,可以使用@FeignClient
内的fallbackFactory
属性。
@FeignClient(name = "testClientWithFactory", url = "http://localhost:${server.port}/",
fallbackFactory = TestFallbackFactory.class)
protected interface TestClientWithFactory {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
Hello getHello();
@RequestMapping(method = RequestMethod.GET, value = "/hellonotfound")
String getException();
}
@Component
static class TestFallbackFactory implements FallbackFactory<FallbackWithFactory> {
@Override
public FallbackWithFactory create(Throwable cause) {
return new FallbackWithFactory();
}
}
static class FallbackWithFactory implements TestClientWithFactory {
@Override
public Hello getHello() {
throw new NoFallbackAvailableException("Boom!", new RuntimeException());
}
@Override
public String getException() {
return "Fixed response";
}
}
1.8. Feign和@Primary
将Feign与Spring Cloud断路器回退一起使用时,ApplicationContext
中存在多个相同类型的bean。这将导致@Autowired
无法工作,因为没有正好一个bean,或者没有一个被标记为主要的bean。为了解决这个问题,Spring Cloud OpenFeign 将所有 Feign 实例标记为@Primary
,以便 Spring Framework 知道要注入哪个 bean。在某些情况下,这可能并不理想。要关闭此行为,请将@FeignClient
的primary
属性设置为false。
@FeignClient(name = "hello", primary = false)
public interface HelloClient {
// methods here
}
1.9. Feign继承支持
Feign 通过单继承接口支持样板 API。这允许将常见操作分组到方便的基接口中。
public interface UserService {
@RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
User getUser(@PathVariable("id") long id);
}
@RestController
public class UserResource implements UserService {
}
package project.user;
@FeignClient("users")
public interface UserClient extends UserService {
}
@FeignClient 接口不应在服务器和客户端之间共享,并且不再支持在类级别使用@RequestMapping 注释@FeignClient 接口。 |
1.10. Feign请求/响应压缩
您可以考虑为Feign请求启用请求或响应GZIP压缩。您可以通过启用以下属性之一来实现:
spring.cloud.openfeign.compression.request.enabled=true
spring.cloud.openfeign.compression.response.enabled=true
Feign请求压缩为您提供了与您可能为Web服务器设置的类似设置
spring.cloud.openfeign.compression.request.enabled=true
spring.cloud.openfeign.compression.request.mime-types=text/xml,application/xml,application/json
spring.cloud.openfeign.compression.request.min-request-size=2048
这些属性允许您选择性地选择压缩的媒体类型和最小请求阈值长度。
由于OkHttpClient使用“透明”压缩,即如果存在content-encoding 或accept-encoding 标头则禁用,因此当类路径上存在feign.okhttp.OkHttpClient 并且spring.cloud.openfeign.okhttp.enabled 设置为true 时,我们不会启用压缩。 |
1.11. Feign日志记录
为创建的每个Feign客户端创建一个日志记录器。默认情况下,日志记录器的名称是用于创建Feign客户端的接口的全限定类名。Feign日志记录仅响应DEBUG
级别。
logging.level.project.user.UserClient: DEBUG
您可以为每个客户端配置的Logger.Level
对象告诉Feign记录多少内容。选项包括:
-
NONE
,不进行日志记录(**默认**)。 -
BASIC
,仅记录请求方法和URL以及响应状态码和执行时间。 -
HEADERS
,记录基本信息以及请求和响应标头。 -
FULL
,记录请求和响应的标头、正文和元数据。
例如,以下内容会将Logger.Level
设置为FULL
@Configuration
public class FooConfiguration {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
1.12. Feign功能支持
Feign功能公开核心Feign组件,以便可以修改这些组件。例如,功能可以获取Client
,对其进行装饰,并将装饰后的实例返回给Feign。对Micrometer的支持就是一个很好的实际例子。参见Micrometer支持。
创建一到多个Capability
bean并将它们放在@FeignClient
配置中,可以注册它们并修改相关客户端的行为。
@Configuration
public class FooConfiguration {
@Bean
Capability customCapability() {
return new CustomCapability();
}
}
1.13. Micrometer支持
如果以下所有条件都为真,则会创建并注册MicrometerObservationCapability
bean,以便Micrometer可以观察您的Feign客户端
-
feign-micrometer
位于类路径上 -
ObservationRegistry
bean可用 -
feign micrometer属性设置为
true
(默认为)-
spring.cloud.openfeign.micrometer.enabled=true
(对于所有客户端) -
spring.cloud.openfeign.client.config.feignName.micrometer.enabled=true
(对于单个客户端)
-
如果您的应用程序已经使用Micrometer,启用此功能就像将feign-micrometer 放到类路径上一样简单。 |
您还可以通过以下任一方式禁用此功能:
-
从类路径中排除
feign-micrometer
-
将其中一个feign micrometer属性设置为
false
-
spring.cloud.openfeign.micrometer.enabled=false
-
spring.cloud.openfeign.client.config.feignName.micrometer.enabled=false
-
spring.cloud.openfeign.micrometer.enabled=false 会禁用**所有**Feign客户端的Micrometer支持,而不管客户端级别标志的值如何:spring.cloud.openfeign.client.config.feignName.micrometer.enabled 。如果要为每个客户端启用或禁用Micrometer支持,请不要设置spring.cloud.openfeign.micrometer.enabled 并使用spring.cloud.openfeign.client.config.feignName.micrometer.enabled 。 |
您还可以通过注册您自己的bean来自定义MicrometerObservationCapability
@Configuration
public class FooConfiguration {
@Bean
public MicrometerObservationCapability micrometerObservationCapability(ObservationRegistry registry) {
return new MicrometerObservationCapability(registry);
}
}
仍然可以使用MicrometerCapability
与Feign(仅限指标支持),您需要禁用Micrometer支持(spring.cloud.openfeign.micrometer.enabled=false
)并创建一个MicrometerCapability
bean
@Configuration
public class FooConfiguration {
@Bean
public MicrometerCapability micrometerCapability(MeterRegistry meterRegistry) {
return new MicrometerCapability(meterRegistry);
}
}
1.14. Feign缓存
如果使用@EnableCaching
注释,则会创建并注册CachingCapability
bean,以便您的Feign客户端识别其接口上的@Cache*
注释
public interface DemoClient {
@GetMapping("/demo/{filterParam}")
@Cacheable(cacheNames = "demo-cache", key = "#keyParam")
String demoEndpoint(String keyParam, @PathVariable String filterParam);
}
您还可以通过属性spring.cloud.openfeign.cache.enabled=false
禁用此功能。
1.15. Feign @QueryMap支持
Spring Cloud OpenFeign 提供了一个等效的 @SpringQueryMap
注解,用于将 POJO 或 Map 参数注释为查询参数映射。
例如,Params
类定义了参数 param1
和 param2
// Params.java
public class Params {
private String param1;
private String param2;
// [Getters and setters omitted for brevity]
}
以下 Feign 客户端使用 @SpringQueryMap
注解使用 Params
类
@FeignClient("demo")
public interface DemoTemplate {
@GetMapping(path = "/demo")
String demoEndpoint(@SpringQueryMap Params params);
}
如果您需要更多地控制生成的查询参数映射,可以实现自定义的 QueryMapEncoder
bean。
1.16. HATEOAS 支持
Spring 提供了一些 API 来创建遵循 HATEOAS 原则的 REST 表示,Spring Hateoas 和 Spring Data REST。
如果您的项目使用 org.springframework.boot:spring-boot-starter-hateoas
启动器或 org.springframework.boot:spring-boot-starter-data-rest
启动器,则默认启用 Feign HATEOAS 支持。
启用 HATEOAS 支持后,Feign 客户端允许序列化和反序列化 HATEOAS 表示模型:EntityModel、CollectionModel 和 PagedModel。
@FeignClient("demo")
public interface DemoTemplate {
@GetMapping(path = "/stores")
CollectionModel<Store> getStores();
}
1.17. Spring @MatrixVariable 支持
Spring Cloud OpenFeign 支持 Spring 的 @MatrixVariable
注解。
如果将映射作为方法参数传递,则通过使用 =
连接映射中的键值对来创建 @MatrixVariable
路径段。
如果传递不同的对象,则使用 =
将 @MatrixVariable
注解中提供的 name
(如果已定义)或带注释的变量名与提供的方法参数连接。
- 重要
-
尽管在服务器端,Spring 不要求用户将路径段占位符的名称命名为与矩阵变量名相同,因为这在客户端过于模糊,Spring Cloud OpenFeign 要求您添加一个名称与
@MatrixVariable
注解中提供的name
(如果已定义)或带注释的变量名匹配的路径段占位符。
例如
@GetMapping("/objects/links/{matrixVars}")
Map<String, List<String>> getObjects(@MatrixVariable Map<String, List<String>> matrixVars);
请注意,变量名和路径段占位符都称为 matrixVars
。
@FeignClient("demo")
public interface DemoTemplate {
@GetMapping(path = "/stores")
CollectionModel<Store> getStores();
}
1.18. Feign CollectionFormat
支持
我们通过提供 @CollectionFormat
注解来支持 feign.CollectionFormat
。您可以使用它通过传递所需的 feign.CollectionFormat
作为注解值来注释 Feign 客户端方法(或整个类以影响所有方法)。
在下面的示例中,使用 CSV
格式而不是默认的 EXPLODED
格式来处理方法。
@FeignClient(name = "demo")
protected interface DemoFeignClient {
@CollectionFormat(feign.CollectionFormat.CSV)
@GetMapping(path = "/test")
ResponseEntity performRequest(String test);
}
1.19. 响应式支持
由于 OpenFeign 项目 目前不支持响应式客户端,例如 Spring WebClient,Spring Cloud OpenFeign 也不支持。一旦核心项目可用,我们将在此处添加对它的支持。
在此之前,我们建议使用 feign-reactive 来支持 Spring WebClient。
1.19.1. 早期初始化错误
我们不建议在应用程序生命周期的早期阶段使用 Feign 客户端,而是在处理配置和初始化 bean 时使用。在 bean 初始化期间使用客户端不受支持。
同样,根据您使用 Feign 客户端的方式,您可能会在启动应用程序时看到初始化错误。要解决此问题,您可以在自动装配客户端时使用 ObjectProvider
。
@Autowired
ObjectProvider<TestFeignClient> testFeignClient;
1.20. Spring Data 支持
如果类路径上存在 Jackson Databind 和 Spring Data Commons,则会自动添加 org.springframework.data.domain.Page
和 org.springframework.data.domain.Sort
的转换器。
要禁用此行为,请设置
spring.cloud.openfeign.autoconfiguration.jackson.enabled=false
有关详细信息,请参阅 org.springframework.cloud.openfeign.FeignAutoConfiguration.FeignJacksonConfiguration
。
1.21. Spring @RefreshScope
支持
如果启用 Feign 客户端刷新,则每个 Feign 客户端都将使用
-
feign.Request.Options
作为刷新范围的 bean 创建。这意味着可以针对任何 Feign 客户端实例刷新诸如connectTimeout
和readTimeout
之类的属性。 -
一个包装在
org.springframework.cloud.openfeign.RefreshableUrl
下的 url。这意味着如果使用spring.cloud.openfeign.client.config.{feignName}.url
属性定义,Feign 客户端的 URL 可以针对任何 Feign 客户端实例进行刷新。
您可以通过 POST /actuator/refresh
刷新这些属性。
默认情况下,Feign 客户端中的刷新行为处于禁用状态。使用以下属性启用刷新行为
spring.cloud.openfeign.client.refresh-enabled=true
请勿使用 @RefreshScope 注解注释 @FeignClient 接口。 |
1.22. OAuth2 支持
可以通过将 spring-boot-starter-oauth2-client
依赖项添加到您的项目并设置以下标志来启用 OAuth2 支持
spring.cloud.openfeign.oauth2.enabled=true
当标志设置为 true 且存在 oauth2 客户端上下文资源详细信息时,将创建一个 OAuth2AccessTokenInterceptor
类的 bean。在每次请求之前,拦截器都会解析所需的访问令牌并将其作为标头包含在内。OAuth2AccessTokenInterceptor
使用 OAuth2AuthorizedClientManager
获取包含 OAuth2AccessToken
的 OAuth2AuthorizedClient
。如果用户使用 spring.cloud.openfeign.oauth2.clientRegistrationId
属性指定了 OAuth2 clientRegistrationId
,则将使用它来检索令牌。如果没有检索到令牌或未指定 clientRegistrationId
,则将使用从 url
主机段检索到的 serviceId
。
- 提示
-
使用
serviceId
作为 OAuth2 clientRegistrationId 方便负载均衡的 Feign 客户端。对于非负载均衡的客户端,基于属性的clientRegistrationId
是一种合适的方法。 - 提示
-
如果您不想使用
OAuth2AuthorizedClientManager
的默认设置,您只需在配置中实例化此类型的 bean。
1.23. 转换负载均衡的 HTTP 请求
您可以使用选定的 ServiceInstance
来转换负载均衡的 HTTP 请求。
对于 Request
,您需要实现并定义 LoadBalancerFeignRequestTransformer
,如下所示
@Bean
public LoadBalancerFeignRequestTransformer transformer() {
return new LoadBalancerFeignRequestTransformer() {
@Override
public Request transformRequest(Request request, ServiceInstance instance) {
Map<String, Collection<String>> headers = new HashMap<>(request.headers());
headers.put("X-ServiceId", Collections.singletonList(instance.getServiceId()));
headers.put("X-InstanceId", Collections.singletonList(instance.getInstanceId()));
return Request.create(request.httpMethod(), request.url(), headers, request.body(), request.charset(),
request.requestTemplate());
}
};
}
如果定义了多个转换器,则按 bean 定义的顺序应用它们。或者,您可以使用 LoadBalancerFeignRequestTransformer.DEFAULT_ORDER
来指定顺序。
1.24. X-Forwarded Headers 支持
可以通过设置以下标志来启用 X-Forwarded-Host
和 X-Forwarded-Proto
支持
spring.cloud.loadbalancer.x-forwarded.enabled=true
1.25. 向 Feign 客户端提供 URL 的支持方式
您可以通过以下任何方式向 Feign 客户端提供 URL
情况 | 示例 | 详情 |
---|---|---|
URL 在 |
|
URL 从注解的 |
URL 在 |
|
URL 从注解的 |
URL 未在 |
|
URL 从配置属性解析,不进行负载均衡。如果 |
URL 未在 |
|
URL 从注解的 |
1.26. AOT 和原生镜像支持
Spring Cloud OpenFeign 支持 Spring AOT 转换和原生镜像,但是,只有在禁用刷新模式、Feign 客户端刷新禁用(默认设置)和 延迟 @FeignClient
属性解析 禁用(默认设置)的情况下才支持。
如果您想在 AOT 或原生镜像模式下运行 Spring Cloud OpenFeign 客户端,请确保将 spring.cloud.refresh.enabled 设置为 false 。 |
如果您想在 AOT 或原生镜像模式下运行 Spring Cloud OpenFeign 客户端,请确保 spring.cloud.openfeign.client.refresh-enabled 未设置为 true 。 |
如果您想在 AOT 或原生镜像模式下运行 Spring Cloud OpenFeign 客户端,请确保 spring.cloud.openfeign.lazy-attributes-resolution 未设置为 true 。 |
但是,如果您通过属性设置 url 值,则可以通过使用 -Dspring.cloud.openfeign.client.config.[clientId].url=[url] 标志运行镜像来覆盖 @FeignClient url 值。为了启用覆盖,还必须通过属性设置 url 值,而不能在构建时设置 @FeignClient 属性。 |