Spring Cloud OpenFeign 功能
Declarative REST Client: Feign
Feign 是一个声明式 Web 服务客户端。它使编写 Web 服务客户端更简单。使用 Feign 需要创建一个界面并进行注释。它支持可插拔的注释,包括 Feign 注释和 JAX-RS 注释。Feign 还支持可插拔编码器和解码器。Spring Cloud 增加了对 Spring MVC 注释及其使用的支持HttpMessage转换器在 Spring Web 中默认使用。
Spring Cloud 集成了 Eureka、Spring Cloud CircuitBreaker 以及 Spring Cloud LoadBalancer,在使用 Feign 时提供负载均衡的 HTTP 客户端。
如何包含假装
要把Feign加入你的项目,可以用Starter和group一起org.springframework.cloud以及工件ID春云启动者开假. 请参阅 Spring Cloud Project 页面,了解如何使用当前的 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();
@GetMapping("/stores")
Page<Store> getStores(Pageable pageable);
@PostMapping(value = "/stores/{storeId}", consumes = "application/json",
params = "mode=upsert")
Store update(@PathVariable("storeId") Long storeId, Store store);
@DeleteMapping("/stores/{storeId:\\d+}")
void delete(@PathVariable Long storeId);
}
在@FeignClient注释字符串值(“上文”存储“)是一个任意的客户端名称,用于创建 Spring Cloud LoadBalancer 客户端。
你也可以用网址属性
(绝对值或仅是一个主机名)。豆子的名字
应用上下文是接口的完全限定名称。
要指定你自己的别名值,可以用限定 符价值
关于@FeignClient注解。
上述负载均衡客户端会想要发现物理地址用于“stores”服务。如果你的应用是 Eureka 客户端,那么它会在 Eureka 服务注册表中解析该服务。如果你不想使用 Eureka,你可以配置服务器列表在你的外部配置中使用SimpleDiscovery客户端.
Spring Cloud OpenFeign 支持 Spring Cloud LoadBalancer 阻挡模式的所有功能。你可以在项目文档中阅读更多相关内容。
使用@EnableFeignClients注释@Configuration-annotated-classes,务必指定客户端的位置,例如:@EnableFeignClients(basePackages = “com.example.clients”)或者明确列出:@EnableFeignClients(clients = InventoryServiceFeignClient.class). |
为了在多模块设置中加载 Spring Feign 客户端豆子,你需要直接指定这些包。
因为工厂豆对象可以在初始上下文刷新前实例化,而 Spring Cloud OpenFeign 客户端的实例化会触发上下文刷新,不应在内部声明工厂豆类。 |
覆盖假装默认
Spring Cloud 在 Feign 支持中的核心概念是命名客户端。每个 Feign 客户端都是组件集合的一部分,这些组件协同工作以按需联系远程服务器,而该集合有一个名称,作为应用开发者,你会用@FeignClient注解。春云创造了一个全新的组合,作为应用上下文按需为每个指定客户使用FeignClientsConfiguration. 这包括(除其他内容外)一个装。译码器一个装。编码器,以及一个装。合同. 可以通过使用contextID属性@FeignClient注解。
Spring Cloud 允许你通过声明额外的配置(在FeignClientsConfiguration) 使用@FeignClient. 例:
@FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient {
//..
}
在这种情况下,客户端是由已经在 中的组件组成的FeignClientsConfiguration与任意FooConfiguration(其中后者会覆盖前者)。
FooConfiguration不需要注释@Configuration.但如果是,那就要注意把它排除在任何@ComponentScan否则,这个配置将成为默认来源装。译码器,装。编码器,装。合同,等等,在指定时。通过将其放在一个独立且不重叠的封装中,可以避免这种情况@ComponentScan或@SpringBootApplication,或者在中可以明确排除@ComponentScan. |
用contextID属性@FeignClient除了更改 的名称外,还要注释
这应用上下文Ensemble,它会覆盖客户端名称的别名
并且它将作为为该客户端创建的配置豆名称的一部分使用。 |
之前,使用网址属性,不需要名称属性。用名称现在是必须的。 |
占位符在名称和网址属性。
@FeignClient(name = "${feign.name}", url = "${feign.url}")
public interface StoreClient {
//..
}
Spring Cloud OpenFeign 默认提供以下 faign 豆子(豆型豆名:类别名称):
-
译码器假解码器:响应实体解码器(该将春季解码器) -
编码器feignEncoder:SpringEncoder -
记录伪造日志作者:Slf4jLogger -
微米观测能力微米观测能力:如果假测微尺位于类路径上,且ObservationRegistry可获得 -
微米级能力微米能力:如果假测微尺位于类路径上,MeterRegistry可得且ObservationRegistry不可用 -
缓存能力缓存能力:如果@EnableCaching使用注释。可以通过以下方式禁用spring.cloud.openfeign.cache.enabled. -
合同假合同:春季Mvc合约 -
假装。建造者伪造者:假装断路器。建造者 -
客户端feignClient:如果 Spring Cloud LoadBalancer 在类路径上,伪阻挡负载均衡器客户端被使用。 如果它们都不在类路径上,则使用默认的 Feign 客户端。
春云启动者开假支持Spring-Cloud-starter-loadbalancer.不过,作为可选依赖,如果你想使用它,必须确保它已经添加到你的项目中。 |
对于支持 Apache HttpClient 5 的 Feign 客户端,确保 HttpClient 5 在类路径上就足够了,但你仍然可以通过设置来禁用 Feign 客户端的使用Spring.cloud.openfeign.httpclient.hc5.enabled自false.
你可以自定义所用的HTTP客户端,提供以下任一的资源org.apache.hc.client5.http.impl.classic.CloseableHttpClient使用Apache HC5时。
你还可以通过在spring.cloud.openfeign.httpclient.xxx性能。那些只用http客户端适用于所有客户,前缀为httpclient.hc5Apache HttpClient 5,以及前缀为httpclient.http2转入 Http2Client。你可以在附录中找到可自定义的完整房产列表。
如果你无法通过属性配置Apache HttpClient 5,有HttpClient5FeignConfiguration.HttpClientBuilderCustomizer用于程序化配置的接口。
Apache HTTP 组件5.4更改了 HTTP/1.1 TLS 升级相关的 HttpClient 默认设置。大多数代理服务器升级都没问题,但你可能会遇到Envoy或Istio的问题。如果你需要恢复之前的行为,可以使用HttpClient5FeignConfiguration.HttpClientBuilderCustomizer如下面示例所示。 |
@Configuration
public class FooConfiguration {
@Bean
public HttpClient5FeignConfiguration.HttpClientBuilderCustomizer httpClientBuilder() {
return (httpClientBuilder) -> {
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
requestConfigBuilder.setProtocolUpgradeEnabled(false);
httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
};
}
}
| 从 Spring Cloud OpenFeign 4 开始,Feign Apache HttpClient 4 不再被支持。我们建议改用Apache HttpClient 5。 |
Spring Cloud OpenFeign 默认不提供以下 Pizza 的 Eagen,但仍会从应用上下文中查找这些类型的 BEANS 以创建 Feign 客户端:
-
Logging工。级别 -
重试者 -
错误解码器 -
请求。选项 -
收藏<请求拦截者> -
赛特工厂 -
QueryMapEncoder -
能力(微米观测能力和缓存能力默认提供)
一颗豆子Retryer.NEVER_RETRY其中类型为重试者默认创建,会禁用重试。
注意这种重试行为与 Feign 默认的不一样,后者会自动重试 IOExceptions,
将其视为瞬态网络相关异常,以及任何来自错误解码器抛出的可重试异常。
制作这种类型的豆子并放入@FeignClient配置(例如:FooConfiguration上面)允许你覆盖描述的每一个咖啡豆。例:
@Configuration
public class FooConfiguration {
@Bean
public Contract feignContract() {
return new feign.Contract.Default();
}
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
return new BasicAuthRequestInterceptor("user", "password");
}
}
这取代了春季Mvc合约跟装。合同。违约并添加一个请求拦截者收藏请求拦截者.
@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
假名本例中指的是@FeignClient 值,也与 有混称@FeignClient 名称和@FeignClient contextID.在负载均衡场景中,它也对应于服务ID服务器应用的访问,用于检索实例。解码器、重试器及其他类的指定类必须在 Spring 上下文中有 bean 或有默认构造函数。
默认配置可在@EnableFeignClients属性defaultConfiguration方式与上述类似。不同的是,这种配置适用于所有 Feign 客户端。
如果你更喜欢用配置属性来配置所有@FeignClient你可以用 创建配置属性默认值假名。
你可以使用spring.cloud.openfeign.client.config.feignName.defaultQueryParameters和spring.cloud.openfeign.client.config.feignName.defaultRequestHeaders指定每个客户端请求时发送的查询参数和头部假名.
application.yml
spring:
cloud:
openfeign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic
如果我们两者都创造@Configuration豆子和配置属性,配置属性会赢。
它会覆盖@Configuration值。但如果你想把优先级改成@Configuration,
你可以改变spring.cloud.openfeign.client.default-to-properties自false.
如果我们想创建多个同名或相同网址的 Feign 客户端
这样它们就会指向同一服务器,但每个服务器的自定义配置不同
我们必须使用contextID属性@FeignClient为了避免被点名
这些配置豆的碰撞。
@FeignClient(contextId = "fooClient", name = "stores", configuration = FooConfiguration.class)
public interface FooClient {
//..
}
@FeignClient(contextId = "barClient", name = "stores", configuration = BarConfiguration.class)
public interface BarClient {
//..
}
也可以配置 FeignClient 不继承父上下文的豆子。
你可以通过覆盖inheritParentConfiguration()在FeignClientConfigurer豆豆将归来false:
@Configuration
public class CustomConfiguration {
@Bean
public FeignClientConfigurer feignClientConfigurer() {
return new FeignClientConfigurer() {
@Override
public boolean inheritParentConfiguration() {
return false;
}
};
}
}
默认情况下,假装客户端不编码斜杠字符。你可以通过设置 的值来改变这种行为/Spring.cloud.openfeign.client.decode-slash自false. |
默认情况下,Feign客户端不会从请求路径中移除尾部斜杠字符。
你可以通过设置 的值来改变这种行为/Spring.cloud.openfeign.client.remove-trailing-slash自true.
请求路径上的尾斜杠移除将成为下一个主要版本的默认行为。 |
超时处理
我们可以在默认客户端和命名客户端上配置超时。OpenFeign 使用两个超时参数:
-
connectTimeout防止因服务器处理时间长而阻塞呼叫者。 -
readTimeout从连接建立时起应用,当返回响应过长时触发。
如果服务器未运行或不可用,数据包会导致连接被拒绝。通信结束时要么是错误消息,要么是备份。这可能发生在connectTimeout如果设定得非常低。执行查找和接收此类数据包所需的时间,导致了这一延迟的很大一部分。它可能会根据涉及DNS查询的远程主机而有所变化。 |
手动创建假客户端
在某些情况下,可能需要以一种不符合的方式定制你的假客户 通过上述方法实现。在这种情况下,你可以用 Faign Builder API 创建客户端。下面是一个例子 该系统创建两个具有相同接口的假客户端,但每个客户端配置为 一台独立的请求拦截器。
@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是客户将要提出请求的服务名称。 |
伪装合同对象定义了哪些注释和值在接口上有效。这
自动接线合同bean 支持 SpringMVC 注释,代替
默认的 Feign 原生注释。不建议将Spring MVC注释和本地Feign注释混用。 |
你也可以使用Builder' 配置 FeignClient 不继承父上下文的豆子。
你可以通过覆盖调用 'inheritParentContext(false) 来实现这一点。在架构工人.
假Spring云断路器支持
如果 Spring Cloud CircuitBreaker 在类路径上,且spring.cloud.openfeign.circuitbreaker.enabled=true,假装会用断路器包裹所有方法。
要按客户端禁用 Spring Cloud CircuitBreaker 支持,请创建一个原版假装。建造者带有“原型”示波器,例如:
@Configuration
public class FooConfiguration {
@Bean
@Scope("prototype")
public Feign.Builder feignBuilder() {
return Feign.builder();
}
}
断路器的名称遵循这一模式<feignClientClassName>#<calledMethod>(<parameterTypes>).当呼叫@FeignClient跟FooClient接口和无参数的调用接口方法为酒吧那么断路器名称为FooClient#bar().
截至2020.0.2,断路器名称模式已从<feignClientName>_<calledMethod>.
用CircuitBreakerNameResolver2020.0.4 引入的断路器名称可保留旧模式。 |
提供 的豆子CircuitBreakerNameResolver你可以更改断路器名称模式。
@Configuration
public class FooConfiguration {
@Bean
public CircuitBreakerNameResolver circuitBreakerNameResolver() {
return (String feignClientName, Target<?> target, Method method) -> feignClientName + "_" + method.getName();
}
}
要启用 Spring Cloud CircuitBreaker 组,请设置spring.cloud.openfeign.circuitbreaker.group.enabled属性到true(默认情况下false).
配置断路器配置配置属性
你可以通过配置属性配置断路器。
例如,如果你有这个 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. |
假弹云断路器备份
Spring Cloud CircuitBreaker 支持备份的概念:当电路开启或出现错误时执行的默认代码路径。为给定的后备启用@FeignClient设置后备属性为实现后备的类名。你还需要声明你的实现是春季豆。
@FeignClient(name = "test", url = "http://localhost:${server.port}/", fallback = Fallback.class)
protected interface TestClient {
@GetMapping("/hello")
Hello getHello();
@GetMapping("/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.
@FeignClient(name = "testClientWithFactory", url = "http://localhost:${server.port}/",
fallbackFactory = TestFallbackFactory.class)
protected interface TestClientWithFactory {
@GetMapping("/hello")
Hello getHello();
@GetMapping("/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";
}
}
假装和@Primary
当使用 Feign 配合 Spring Cloud CircuitBreaker 的备用时,会有多个豆子在应用上下文同类型。这将导致@Autowired因为没有一颗豆子,或者没有标记为主豆子,所以不起作用。为了解决这个问题,Spring Cloud OpenFeign 会将所有 Feign 实例标记为@Primary,这样Spring Framework就能知道该注入哪个豆子。在某些情况下,这可能并不理想。要关闭此行为,请设置主要属性@FeignClient太虚假了。
@FeignClient(name = "hello", primary = false)
public interface HelloClient {
// methods here
}
假装继承支持
Feign 支持通过单继承接口的样板 API。 这使得将常用作分组到方便的基界面中。
public interface UserService {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") long id);
}
@RestController
public class UserResource implements UserService {
}
@FeignClient("users")
public interface UserClient extends UserService {
}
@FeignClient接口不应在服务器和客户端之间共享,注释也不应@FeignClient与@RequestMapping班级层面已不再支持。 |
假装请求/响应压缩
你可以考虑启用请求或响应的GZIP压缩功能,用于你的 假装请求。你可以通过启用以下一个属性来实现:
spring.cloud.openfeign.compression.request.enabled=true
spring.cloud.openfeign.compression.response.enabled=true
假请求压缩会给你类似你为网络服务器设置的设置:
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
这些属性使你能够选择压缩媒介类型和最小请求阈值长度。
当请求匹配 in 中设定的哑剧类型时spring.cloud.openfeign.compression.request.mime-types以及 的大小Spring.cloud.openfeign.compression.request.min-request-size,spring.cloud.openfeign.compression.request.enabled=true结果是请求中会添加压缩头。
头部的功能是向服务器信号,客户端期望有一个压缩的主体。服务器端应用有责任根据客户端提供的头部提供压缩正体。
假装Logging
每个创建的 Feign 客户端都会创建一个日志器。默认情况下,日志日志的名称是用于创建 Feign 客户端接口的完整类名称。假装记录只对调试水平。
logging.level.project.user.UserClient: DEBUG
这Logging工。级别你可以为每个客户端配置的对象,告诉 Feign 要记录多少。可选方案如下:
-
没有,无日志记录(默认)。 -
基本只记录请求方法和URL,以及响应状态代码和执行时间。 -
头,记录基本信息以及请求和响应头部。 -
满记录请求和响应的头部、正文和元数据。
例如,以下设置将使Logging工。级别自满:
@Configuration
public class FooConfiguration {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
假装能力支持
Feign 能力会暴露核心 Feign 组件,以便这些组件被修改。例如,能力可以取客户端装饰它,然后把装饰好的实例还给Feign。
Micrometer 的支持是一个很好的现实例子。参见微尺支撑。
创建一个或多个能力豆子并放入@FeignClient配置允许你注册它们并修改相关客户端的行为。
@Configuration
public class FooConfiguration {
@Bean
Capability customCapability() {
return new CustomCapability();
}
}
微米支持
如果以下所有条件都成立,则微米观测能力豆子的创建和注册是为了让你的 Fiign 客户端被 Micrometer 可观察到:
-
假测微尺位于类路径上 -
一个
ObservationRegistry豆子豆可获得 -
假微米的属性设置为
true(默认)-
spring.cloud.openfeign.micrometer.enabled=true(针对所有客户) -
spring.cloud.openfeign.client.config.feignName.micrometer.enabled=true(针对单个客户)
-
如果您的应用程序已经使用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. |
你也可以自定义微米观测能力通过注册你自己的豆子:
@Configuration
public class FooConfiguration {
@Bean
public MicrometerObservationCapability micrometerObservationCapability(ObservationRegistry registry) {
return new MicrometerObservationCapability(registry);
}
}
它仍然可以使用微米级能力使用Feign(仅支持公制)时,你需要关闭对Micrometer的支持(spring.cloud.openfeign.micrometer.enabled=false)并生成微米级能力豆:
@Configuration
public class FooConfiguration {
@Bean
public MicrometerCapability micrometerCapability(MeterRegistry meterRegistry) {
return new MicrometerCapability(meterRegistry);
}
}
假缓存
如果@EnableCaching使用注释,a缓存能力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.
春季@RequestMapping支持
Spring Cloud OpenFeign 支持 Spring@RequestMapping注释及其派生注释(例如@GetMapping,@PostMapping以及其他)支持。
属性@RequestMapping注释(包括值,方法,参数,头,消耗和生产)被解析为春季Mvc合约作为请求的内容。
请考虑以下例子:
定义一个接口,使用以下条件参数属性。
@FeignClient("demo")
public interface DemoTemplate {
@PostMapping(value = "/stores/{storeId}", params = "mode=upsert")
Store update(@PathVariable("storeId") Long storeId, Store store);
}
在上述示例中,请求URL解析为/stores/storeId?mode=upsert.
params 属性还支持使用多个key=value或者只有一个钥匙:
-
什么时候
参数 = { “key1=v1”, “key2=v2” },请求URL解析为/stores/storeId?key1=v1&key2=v2. -
什么时候
参数 = “密钥”,请求URL解析为/stores/storeId?key.
假装@QueryMap支持
Spring Cloud OpenFeign 提供了对应的服务@SpringQueryMap注释,即用于将POJO或Map参数作为查询参数映射进行注释。
例如,参数类定义参数第1段和第2段:
// Params.java
public class Params {
private String param1;
private String param2;
// [Getters and setters omitted for brevity]
}
以下 Feign 客户端使用参数通过使用@SpringQueryMap注解:
@FeignClient("demo")
public interface DemoTemplate {
@GetMapping(path = "/demo")
String demoEndpoint(@SpringQueryMap Params params);
}
如果你需要对生成的查询参数映射有更多控制,可以实现自定义的QueryMapEncoder豆。
HATEOAS 支持
Spring 提供一些 API,用于创建遵循 HATEOAS 原则、Spring Hateoas 和 Spring Data REST 的 REST 表示。
如果你的项目使用org.springframework.boot:spring-boot-starter-hateoas起动机 或者org.springframework.boot:spring-boot-starter-data-rest初始阶段,默认启用了 Faign HATEOAS 支持。
启用 HATEOAS 支持后,Feign 客户端可以序列化并反序列化 HATEOAS 表示模型:EntityModel、CollectionModel 和 PagedModel。
@FeignClient("demo")
public interface DemoTemplate {
@GetMapping(path = "/stores")
CollectionModel<Store> getStores();
}
春季@MatrixVariable支持
Spring Cloud OpenFeign 支持 Spring@MatrixVariable注解。
如果将映射作为方法参数传递,则@MatrixVariable路径段通过将映射中的键值对与 连接来创建。=
如果传递的是不同的对象,则名称提供于@MatrixVariable注释(如定义)或注释变量名为与所提供的方法参数结合。=
- 重要
-
尽管在服务器端,Spring 不要求用户将路径段占位符命名为与矩阵变量名称相同的,因为在客户端会过于模糊,但 Spring Cloud OpenFeign 要求你添加一个路径段占位符,其名称与
名称提供于@MatrixVariable注释(如定义)或注释变量名称。
例如:
@GetMapping("/objects/links/{matrixVars}")
Map<String, List<String>> getObjects(@MatrixVariable Map<String, List<String>> matrixVars);
注意变量名和路径段占位符均被调用matrixVar.
@FeignClient("demo")
public interface DemoTemplate {
@GetMapping(path = "/stores")
CollectionModel<Store> getStores();
}
装合集格式支持
我们支持装。 合集格式通过提供@CollectionFormat注解。 你可以通过传递所需的装。 合集格式作为注释值。
在以下示例中,CSV格式取代默认爆炸处理这个方法。
@FeignClient(name = "demo")
protected interface DemoFeignClient {
@CollectionFormat(feign.CollectionFormat.CSV)
@GetMapping(path = "/test")
ResponseEntity performRequest(String test);
}
响应式支持
由于在 Spring Cloud OpenFeign 积极开发时,OpenFeign 项目不支持像 Spring WebClient 这样的被动客户端,因此 Spring Cloud OpenFeign 也无法添加此类支持。
由于 Spring Cloud OpenFeign 项目现已被视为功能完整,即使上游项目支持,我们也不打算添加支持。我们建议迁移到 Spring HTTP Service Clients。那里支持阻挡和响应式堆栈。
春季数据支持
如果 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细节。
Spring@RefreshScope支持
如果启用了 Feign 客户端刷新功能,每个 Feign 客户端将创建:
-
装。 请求。选项作为一个刷新范围的豆。这意味着以下属性connectTimeout和readTimeout可以对任何 Feign 客户端实例进行刷新。 -
一个包裹在下面的网址
org.springframework.cloud.openfeign.RefreshableUrl.这意味着如果定义了 Feign 客户端的 URL,也就是 跟spring.cloud.openfeign.client.config.{feignName}.url属性,可以对任何 Feign 客户端实例进行刷新。
你可以通过以下方式刷新这些属性POST /执行器/刷新.
默认情况下,Feign客户端的刷新行为是被禁用的。请使用以下属性来启用刷新行为:
spring.cloud.openfeign.client.refresh-enabled=true
不要对@FeignClient与@RefreshScope注解。 |
OAuth2 支持
可以通过添加Spring-boot-starter-oAuth2-client对项目的依赖性以及设置以下flag:
spring.cloud.openfeign.oauth2.enabled=true
当标志设置为true,且OUuS2客户端上下文资源细节存在时,这是一个类别的“豆子”。OAuth2AccessTokenInterceptor被创造出来。在每次请求之前,拦截者解析所需的访问Tokens并将其作为头部包含。OAuth2AccessTokenInterceptor使用OAuth2AuthorizedClientManager要获得OAuth2AuthorizedClient满足OAuth2AccessToken.如果用户指定了OAuth2clientRegistrationId(客户注册ID使用spring.cloud.openfeign.oauth2.clientRegistrationId属性,它将被用来检索该Tokens。如果Tokens未被检索或clientRegistrationId(客户注册ID尚未具体说明,服务ID检索自网址将使用主持板块。
- 提示
-
使用
服务ID作为 OAuth2 客户端 registrationId,对于负载均衡的 Feign 客户端来说非常方便。对于非负载均衡的,基于属性的clientRegistrationId(客户注册ID是一种合适的方法。 - 提示
-
如果你不想使用默认设置
OAuth2AuthorizedClientManager你可以在配置中实例化这种类型的豆子。
转换负载均衡的HTTP请求
你可以使用选定的ServiceInstance以转换负载均衡的HTTP请求。
为请求你需要实现并定义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());
}
};
}
如果定义了多个转换器,则按定义豆子的顺序应用。
或者,你可以使用LoadBalancerFeignRequestTransformer.DEFAULT_ORDER以指定顺序。
支持为假客户端提供URL的方法
您可以通过以下任一方式为 Feign 客户端提供 URL:
| 箱 | 示例 | 详 |
|---|---|---|
该网址在 |
|
该URL由 |
该网址在 |
|
该URL由 |
该网址未在 |
|
URL通过配置属性解析,无需负载均衡。如果 |
该URL也未在 |
|
该URL解析为 |
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(春.cloud.openfeign.lazy-attributes-resolution)未被设置为true. |
然而,如果你设置网址通过属性,可以覆盖@FeignClient 网址通过将图像运行为-Dspring.cloud.openfeign.client.config.[clientId].url=[url]旗。为了实现覆盖,需要网址值还必须通过属性设置,而不是@FeignClient属性在构建时间内。 |
配置属性
要查看所有与 Spring Cloud OpenFeign 相关的配置属性列表,请查看附录页面。