该版本仍在开发中,尚未被视为稳定。最新稳定版请使用Spring Cloud OpenFeign 5.0.0spring-doc.cadn.net.cn

Spring Cloud OpenFeign 功能

Declarative REST Client: Feign

Feign 是一个声明式网络服务客户端。 它让编写网络服务客户端变得更容易。 使用 Feign 创建一个界面并做注释。 它支持可插拔的注释,包括 Feign 注释和 JAX-RS 注释。 Feign 还支持可插拔的编码器和解码器。 Spring Cloud 增加了对 Spring MVC 注释及其使用的支持HttpMessage转换器在 Spring Web 中默认使用。 Spring Cloud 集成了 Eureka、Spring Cloud CircuitBreaker 以及 Spring Cloud LoadBalancer,在使用 Feign 时提供负载均衡的 HTTP 客户端。spring-doc.cadn.net.cn

如何包含假装

要把Feign加入你的项目,可以用Starter和group一起org.springframework.cloud以及工件ID春云启动者开假.请参阅 Spring Cloud Project 页面,了解如何使用当前的 Spring Cloud 发布列车来设置你的构建系统。spring-doc.cadn.net.cn

示例Spring Boot应用spring-doc.cadn.net.cn

@SpringBootApplication
@EnableFeignClients
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}
StoreClient.java
@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注解。spring-doc.cadn.net.cn

上述负载均衡客户端会希望发现物理地址 用于“商店”服务。如果你的应用是Eureka客户端,那么 它会在 Eureka 服务注册表中解析该服务。如果你 不想用Eureka,你可以配置服务器列表 在你的外部配置中,使用SimpleDiscovery客户端.spring-doc.cadn.net.cn

Spring Cloud OpenFeign 支持 Spring Cloud LoadBalance 的阻挡模式所有功能。你可以在项目文档中了解更多相关内容。spring-doc.cadn.net.cn

使用@EnableFeignClients注释@Configuration-annotated-classes,务必指定客户端的位置,例如:@EnableFeignClients(basePackages = “com.example.clients”)或者明确列出:@EnableFeignClients(clients = InventoryServiceFeignClient.class).

为了在多模块设置中加载 Spring Feign 客户端豆子,你需要直接指定这些包。spring-doc.cadn.net.cn

因为工厂豆对象可以在初始上下文刷新前实例化,而 Spring Cloud OpenFeign 客户端的实例化会触发上下文刷新,不应在内部声明工厂豆类。

属性解析模式

创作过程中客户端 Beans,我们通过@FeignClient注解。截至4.x,这些值正在积极被解决。这对大多数用例来说是个不错的解决方案,同时也支持AOT支持。spring-doc.cadn.net.cn

如果你需要对属性进行懒惰解析,可以设置spring.cloud.openfeign.lazy-attributes-resolution(春.cloud.openfeign.lazy-attributes-resolution)财产价值为true.spring-doc.cadn.net.cn

对于 Spring Cloud Contract 测试集成,应使用懒惰属性解析。

覆盖假装默认

Spring Cloud 在 Feign 支持中的核心概念是命名客户端。每个 Feign 客户端都是组件集合的一部分,这些组件协同工作以按需联系远程服务器,而该集合有一个名称,作为应用开发者,你会用@FeignClient注解。春云创造了一个全新的组合,作为应用上下文按需为每个指定客户使用FeignClientsConfiguration.这包括(除其他内容外)一个装。译码器一个装。编码器,以及一个装。合同. 可以通过使用contextID属性@FeignClient注解。spring-doc.cadn.net.cn

Spring Cloud 允许你通过声明额外的配置(在FeignClientsConfiguration) 使用@FeignClient.例:spring-doc.cadn.net.cn

@FeignClient(name = "stores", configuration = FooConfiguration.class)
public interface StoreClient {
	//..
}

在这种情况下,客户端是由已经在 中的组件组成的FeignClientsConfiguration与任意FooConfiguration(其中后者会覆盖前者)。spring-doc.cadn.net.cn

FooConfiguration不需要注释@Configuration.但如果是,那就要注意把它排除在任何@ComponentScan否则,这个配置将成为默认来源装。译码器,装。编码器,装。合同,等等,在指定时。通过将其放在一个独立且不重叠的封装中,可以避免这种情况@ComponentScan@SpringBootApplication,或者在中可以明确排除@ComponentScan.
contextID属性@FeignClient除了更改 的名称外,还要注释 这应用上下文Ensemble,它会覆盖客户端名称的别名 并且它将作为为该客户端创建的配置豆名称的一部分使用。
之前,使用网址属性,不需要名称属性。用名称现在是必须的。

占位符在名称网址属性。spring-doc.cadn.net.cn

@FeignClient(name = "${feign.name}", url = "${feign.url}")
public interface StoreClient {
	//..
}

Spring Cloud OpenFeign 默认提供以下 faign 豆子(豆型豆名:类别名称):spring-doc.cadn.net.cn

  • 译码器假解码器:响应实体解码器(该将春季解码器)spring-doc.cadn.net.cn

  • 编码器feignEncoder:SpringEncoderspring-doc.cadn.net.cn

  • 记录伪造日志作者:Slf4jLoggerspring-doc.cadn.net.cn

  • 微米观测能力微米观测能力:如果假测微尺位于类路径上,且ObservationRegistry可获得spring-doc.cadn.net.cn

  • 微米级能力微米能力:如果假测微尺位于类路径上,MeterRegistry可得且ObservationRegistry不可用spring-doc.cadn.net.cn

  • 缓存能力缓存能力:如果@EnableCaching使用注释。可以通过以下方式禁用spring.cloud.openfeign.cache.enabled.spring-doc.cadn.net.cn

  • 合同假合同:春季Mvc合约spring-doc.cadn.net.cn

  • 假装。建造者伪造者:假装断路器。建造者spring-doc.cadn.net.cn

  • 客户端feignClient:如果 Spring Cloud LoadBalancer 在类路径上,伪阻挡负载均衡器客户端被使用。 如果它们都不在类路径上,则使用默认的 Feign 客户端。spring-doc.cadn.net.cn

春云启动者开假支持Spring-Cloud-starter-loadbalancer.不过,作为可选依赖,如果你想使用它,必须确保它已经添加到你的项目中。

要使用 OkHttpClient 支持的 Feign 客户端和 Http2Client 假客户端,确保你想使用的客户端位于类路径上,并且设置为spring.cloud.openfeign.ok.enabledspring.cloud.openfeign.http2client.enabledtrue分别。spring-doc.cadn.net.cn

对于支持 Apache HttpClient 5 的 Feign 客户端,确保 HttpClient 5 在类路径上就足够了,但你仍然可以通过设置来禁用 Feign 客户端的使用Spring.cloud.openfeign.httpclient.hc5.enabledfalse. 你可以自定义所用的HTTP客户端,提供以下任一的资源org.apache.hc.client5.http.impl.classic.CloseableHttpClient使用Apache HC5时。spring-doc.cadn.net.cn

你还可以通过在spring.cloud.openfeign.httpclient.xxx性能。那些只用http客户端适用于所有客户,前缀为httpclient.hc5到 Apache HttpClient 5,即前缀为httpclient.okhttp对 OkHttpClient 以及前缀为httpclient.http2转入 Http2Client。你可以在附录中找到可自定义的完整房产列表。 如果你无法通过属性配置Apache HttpClient 5,有HttpClient5FeignConfiguration.HttpClientBuilderCustomizer用于程序化配置的接口。spring-doc.cadn.net.cn

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 客户端:spring-doc.cadn.net.cn

一颗豆子Retryer.NEVER_RETRY其中类型为重试者默认创建,会禁用重试。 注意这种重试行为与 Feign 默认的不一样,后者会自动重试 IOExceptions, 将其视为瞬态网络相关异常,以及任何来自错误解码器抛出的可重试异常。spring-doc.cadn.net.cn

制作这种类型的豆子并放入@FeignClient配置(例如:FooConfiguration上面)允许你覆盖描述的每一个咖啡豆。例:spring-doc.cadn.net.cn

@Configuration
public class FooConfiguration {
	@Bean
	public Contract feignContract() {
		return new feign.Contract.Default();
	}

	@Bean
	public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
		return new BasicAuthRequestInterceptor("user", "password");
	}
}

这取代了春季Mvc合约装。合同。违约并添加一个请求拦截者收藏请求拦截者.spring-doc.cadn.net.cn

@FeignClient也可以通过配置属性进行配置。spring-doc.cadn.net.cn

application.ymlspring-doc.cadn.net.cn

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 或有默认构造函数。spring-doc.cadn.net.cn

默认配置可在@EnableFeignClients属性defaultConfiguration方式与上述类似。不同的是,这种配置适用于所有 Feign 客户端。spring-doc.cadn.net.cn

如果你更喜欢用配置属性来配置所有@FeignClient你可以用 创建配置属性默认值假名。spring-doc.cadn.net.cn

你可以使用spring.cloud.openfeign.client.config.feignName.defaultQueryParametersspring.cloud.openfeign.client.config.feignName.defaultRequestHeaders指定每个客户端请求时发送的查询参数和头部假名.spring-doc.cadn.net.cn

application.ymlspring-doc.cadn.net.cn

spring:
	cloud:
		openfeign:
			client:
				config:
					default:
						connectTimeout: 5000
						readTimeout: 5000
						loggerLevel: basic

如果我们两者都创造@Configuration豆子和配置属性,配置属性会赢。 它会覆盖@Configuration值。但如果你想把优先级改成@Configuration, 你可以改变spring.cloud.openfeign.client.default-to-propertiesfalse.spring-doc.cadn.net.cn

如果我们想创建多个同名或相同网址的 Feign 客户端 这样它们就会指向同一服务器,但每个服务器的自定义配置不同 我们必须使用contextID属性@FeignClient为了避免被点名 这些配置豆的碰撞。spring-doc.cadn.net.cn

@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:spring-doc.cadn.net.cn

@Configuration
public class CustomConfiguration {
	@Bean
	public FeignClientConfigurer feignClientConfigurer() {
		return new FeignClientConfigurer() {
			@Override
			public boolean inheritParentConfiguration() {
				 return false;
			}
		};
	}
}
默认情况下,假装客户端不编码斜杠字符。你可以通过设置 的值来改变这种行为/Spring.cloud.openfeign.client.decode-slashfalse.
默认情况下,Feign客户端不会从请求路径中移除尾部斜杠字符。 你可以通过设置 的值来改变这种行为/Spring.cloud.openfeign.client.remove-trailing-slashtrue. 请求路径上的尾斜杠移除将成为下一个主要版本的默认行为。

SpringEncoder配置

SpringEncoder我们提供的,我们设定用于二进制内容类型的字符集和UTF-8为其他所有的。spring-doc.cadn.net.cn

你可以修改这种行为,从以下条件推导出字符集内容类型通过设置 的值来替代 首部字符集Spring.cloud.openfeign.encoder.charset-from-content-typetrue.spring-doc.cadn.net.cn

超时处理

我们可以在默认客户端和命名客户端上配置超时。OpenFeign 使用两个超时参数:spring-doc.cadn.net.cn

如果服务器未运行或不可用,数据包会导致连接被拒绝。通信结束时要么是错误消息,要么是备份。这可能发生在connectTimeout如果设定得非常低。执行查找和接收此类数据包所需的时间,导致了这一延迟的很大一部分。它可能会根据涉及DNS查询的远程主机而有所变化。

手动创建假客户端

在某些情况下,可能需要以一种不符合的方式定制你的假客户 通过上述方法实现。在这种情况下,你可以用 Faign Builder API 创建客户端。下面是一个例子 该系统创建两个具有相同接口的假客户端,但每个客户端配置为 一台独立的请求拦截器。spring-doc.cadn.net.cn

@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-doc.cadn.net.cn

假Spring云断路器支持

如果 Spring Cloud CircuitBreaker 在类路径上,且spring.cloud.openfeign.circuitbreaker.enabled=true,假装会用断路器包裹所有方法。spring-doc.cadn.net.cn

要按客户端禁用 Spring Cloud CircuitBreaker 支持,请创建一个原版假装。建造者带有“原型”示波器,例如:spring-doc.cadn.net.cn

@Configuration
public class FooConfiguration {
	@Bean
	@Scope("prototype")
	public Feign.Builder feignBuilder() {
		return Feign.builder();
	}
}

断路器的名称遵循这一模式<feignClientClassName>#<calledMethod>(<parameterTypes>). 当呼叫@FeignClientFooClient接口和无参数的调用接口方法为酒吧那么断路器名称为FooClient#bar().spring-doc.cadn.net.cn

截至2020.0.2,断路器名称模式已从<feignClientName>_<calledMethod>. 用CircuitBreakerNameResolver2020.0.4 引入的断路器名称可保留旧模式。

提供 的豆子CircuitBreakerNameResolver你可以更改断路器名称模式。spring-doc.cadn.net.cn

@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).spring-doc.cadn.net.cn

配置断路器配置配置属性

你可以通过配置属性配置断路器。spring-doc.cadn.net.cn

例如,如果你有这个 Feign 客户端spring-doc.cadn.net.cn

@FeignClient(url = "http://localhost:8080")
public interface DemoClient {

    @GetMapping("demo")
    String getDemo();
}

你可以用配置属性来配置,具体作如下spring-doc.cadn.net.cn

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.enabledfalse.

假弹云断路器备份

Spring Cloud CircuitBreaker 支持备用的概念:当电路开启或出现错误时执行的默认代码路径。为给定的某一启用备援@FeignClient设置后备属性为实现备回的类名。你还需要声明你的实现为 Spring Bean。spring-doc.cadn.net.cn

@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.spring-doc.cadn.net.cn

@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 会知道要注入哪个 bean。在某些情况下,这可能并不理想。要关闭此行为,请设置主要属性@FeignClient太虚假了。spring-doc.cadn.net.cn

@FeignClient(name = "hello", primary = false)
public interface HelloClient {
	// methods here
}

假装继承支持

Feign 支持通过单继承接口的样板 API。这使得将常见作分组到方便的基础接口中。spring-doc.cadn.net.cn

UserService.java
public interface UserService {

	@GetMapping("/users/{id}")
	User getUser(@PathVariable("id") long id);
}
UserResource.java
@RestController
public class UserResource implements UserService {

}
UserClient.java
@FeignClient("users")
public interface UserClient extends UserService {

}
@FeignClient接口不应在服务器和客户端之间共享,注释也不应@FeignClient@RequestMapping班级层面已不再支持。

假装请求/响应压缩

你可以考虑为你的假装请求启用请求或响应 GZIP 压缩功能。你可以通过启用以下属性实现:spring-doc.cadn.net.cn

spring.cloud.openfeign.compression.request.enabled=true
spring.cloud.openfeign.compression.response.enabled=true

假请求压缩会给你类似你为网络服务器设置的设置:spring-doc.cadn.net.cn

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

这些属性使你能够选择压缩媒介类型和最小请求阈值长度。spring-doc.cadn.net.cn

当请求匹配 in 中设定的哑剧类型时spring.cloud.openfeign.compression.request.mime-types以及 的大小Spring.cloud.openfeign.compression.request.min-request-size,spring.cloud.openfeign.compression.request.enabled=true结果是请求中会添加压缩头。 头部的功能是向服务器信号,客户端期望有一个压缩的主体。服务器端应用有责任根据客户端提供的头部提供压缩正体。spring-doc.cadn.net.cn

由于 OkHttpClient 使用“透明”压缩,如果内容编码接受编码如果有 头部,我们不会启用压缩feign.okhttp.OkHttpClient存在于类路径上,且spring.cloud.openfeign.ok.enabled设置为true.

假装Logging

每个创建的 Feign 客户端都会创建一个日志器。默认情况下,日志日志的名称是用于创建 Feign 客户端接口的完整类名称。假装记录只对调试水平。spring-doc.cadn.net.cn

application.yml
logging.level.project.user.UserClient: DEBUG

Logging工。级别你可以为每个客户端配置的对象,告诉 Feign 要记录多少。可选方案如下:spring-doc.cadn.net.cn

例如,以下设置将使Logging工。级别:spring-doc.cadn.net.cn

@Configuration
public class FooConfiguration {
	@Bean
	Logger.Level feignLoggerLevel() {
		return Logger.Level.FULL;
	}
}

假装能力支持

Feign 能力会暴露核心 Feign 组件,以便这些组件被修改。例如,能力可以取客户端装饰它,然后把装饰好的实例还给Feign。 Micrometer 的支持是一个很好的现实例子。参见微尺支撑spring-doc.cadn.net.cn

创建一个或多个能力豆子并放入@FeignClient配置允许你注册它们并修改相关客户端的行为。spring-doc.cadn.net.cn

@Configuration
public class FooConfiguration {
	@Bean
	Capability customCapability() {
		return new CustomCapability();
	}
}

微米支持

如果以下所有条件都成立,则微米观测能力豆子的创建和注册是为了让你的 Fiign 客户端被 Micrometer 可观察到:spring-doc.cadn.net.cn

如果您的应用程序已经使用Micrometer,启用此功能只需放置假测微尺进入你的课程路径。

你也可以通过以下方式禁用该功能:spring-doc.cadn.net.cn

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.

你也可以自定义微米观测能力通过注册你自己的豆子:spring-doc.cadn.net.cn

@Configuration
public class FooConfiguration {
	@Bean
	public MicrometerObservationCapability micrometerObservationCapability(ObservationRegistry registry) {
		return new MicrometerObservationCapability(registry);
	}
}

它仍然可以使用微米级能力使用Feign(仅支持公制)时,你需要关闭对Micrometer的支持(spring.cloud.openfeign.micrometer.enabled=false)并生成微米级能力豆:spring-doc.cadn.net.cn

@Configuration
public class FooConfiguration {
	@Bean
	public MicrometerCapability micrometerCapability(MeterRegistry meterRegistry) {
		return new MicrometerCapability(meterRegistry);
	}
}

假缓存

如果@EnableCaching使用注释,a缓存能力BEAN 的创建和注册是为了让你的 Feign 客户能够识别@Cache*其界面上的注释:spring-doc.cadn.net.cn

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.spring-doc.cadn.net.cn

春季@RequestMapping支持

Spring Cloud OpenFeign 支持 Spring@RequestMapping注释及其派生注释(例如@GetMapping,@PostMapping以及其他)支持。 属性@RequestMapping注释(包括,方法,参数,,消耗生产)被解析为春季Mvc合约作为请求的内容。spring-doc.cadn.net.cn

请考虑以下例子:spring-doc.cadn.net.cn

定义一个接口,使用以下条件参数属性。spring-doc.cadn.net.cn

@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或者只有一个钥匙:
spring-doc.cadn.net.cn

  • 什么时候参数 = { “key1=v1”, “key2=v2” },请求URL解析为/stores/storeId?key1=v1&key2=v2.spring-doc.cadn.net.cn

  • 什么时候参数 = “密钥”,请求URL解析为/stores/storeId?key.spring-doc.cadn.net.cn

假装@QueryMap支持

Spring Cloud OpenFeign 提供了对应的服务@SpringQueryMap注释,即用于将POJO或Map参数作为查询参数映射进行注释。spring-doc.cadn.net.cn

例如,参数类定义参数第1段第2段:spring-doc.cadn.net.cn

// Params.java
public class Params {
	private String param1;
	private String param2;

	// [Getters and setters omitted for brevity]
}

以下 Feign 客户端使用参数通过使用@SpringQueryMap注解:spring-doc.cadn.net.cn

@FeignClient("demo")
public interface DemoTemplate {

	@GetMapping(path = "/demo")
	String demoEndpoint(@SpringQueryMap Params params);
}

如果你需要对生成的查询参数映射有更多控制,可以实现自定义的QueryMapEncoder豆。spring-doc.cadn.net.cn

HATEOAS 支持

Spring 提供一些 API,用于创建遵循 HATEOAS 原则、Spring HateoasSpring Data REST 的 REST 表示。spring-doc.cadn.net.cn

如果你的项目使用org.springframework.boot:spring-boot-starter-hateoas起动机 或者org.springframework.boot:spring-boot-starter-data-rest初始阶段,默认启用了 Faign HATEOAS 支持。spring-doc.cadn.net.cn

启用 HATEOAS 支持后,Feign 客户端可以序列化并反序列化 HATEOAS 表示模型:EntityModelCollectionModelPagedModelspring-doc.cadn.net.cn

@FeignClient("demo")
public interface DemoTemplate {

	@GetMapping(path = "/stores")
	CollectionModel<Store> getStores();
}

春季@MatrixVariable支持

Spring Cloud OpenFeign 支持 Spring@MatrixVariable注解。spring-doc.cadn.net.cn

如果将映射作为方法参数传递,则@MatrixVariable路径段通过将映射中的键值对与 连接来创建。=spring-doc.cadn.net.cn

如果传递的是不同的对象,则名称提供于@MatrixVariable注释(如定义)或注释变量名为与所提供的方法参数结合。=spring-doc.cadn.net.cn

重要

尽管在服务器端,Spring 不要求用户将路径段占位符命名为与矩阵变量名称相同的,因为在客户端会过于模糊,但 Spring Cloud OpenFeign 要求你添加一个路径段占位符,其名称与名称提供于@MatrixVariable注释(如定义)或注释变量名称。spring-doc.cadn.net.cn

@GetMapping("/objects/links/{matrixVars}")
Map<String, List<String>> getObjects(@MatrixVariable Map<String, List<String>> matrixVars);

注意变量名和路径段占位符均被调用matrixVar.spring-doc.cadn.net.cn

@FeignClient("demo")
public interface DemoTemplate {

	@GetMapping(path = "/stores")
	CollectionModel<Store> getStores();
}

合集格式支持

我们支持装。 合集格式通过提供@CollectionFormat注解。 你可以通过传递所需的装。 合集格式作为注释值。spring-doc.cadn.net.cn

在以下示例中,CSV格式取代默认爆炸处理这个方法。spring-doc.cadn.net.cn

@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-doc.cadn.net.cn

由于 Spring Cloud OpenFeign 项目现在被视为功能完整,即使上游项目支持也没有计划添加。我们建议迁移到 Spring Interface Clients。那里支持阻挡和被动堆栈。spring-doc.cadn.net.cn

早期初始化错误

我们不建议在应用生命周期的早期阶段使用Feign客户端,尤其是在处理配置和初始化豆子时。不支持在豆子初始化时使用客户端。spring-doc.cadn.net.cn

同样,根据你如何使用 Feign 客户端,启动应用时可能会出现初始化错误。为了解决这个问题,你可以使用对象提供者在为客户自动接线时。spring-doc.cadn.net.cn

@Autowired
ObjectProvider<TestFeignClient> testFeignClient;

春季数据支持

如果 Jackson Databind 和 Spring Data Commons 在类路径上,则org.springframework.data.domain.Pageorg.springframework.data.domain.Sort将自动添加。spring-doc.cadn.net.cn

要禁用该行为集spring-doc.cadn.net.cn

spring.cloud.openfeign.autoconfiguration.jackson.enabled=false

org.springframework.cloud.openfeign.FeignAutoConfiguration.FeignJacksonConfiguration细节。spring-doc.cadn.net.cn

Spring@RefreshScope支持

如果启用了 Feign 客户端刷新功能,每个 Feign 客户端将创建:spring-doc.cadn.net.cn

  • 装。 请求。选项作为一个刷新范围的豆。这意味着以下属性connectTimeoutreadTimeout可以对任何 Feign 客户端实例进行刷新。spring-doc.cadn.net.cn

  • 一个包裹在下面的网址org.springframework.cloud.openfeign.RefreshableUrl.这意味着如果定义了 Feign 客户端的 URL,也就是 跟spring.cloud.openfeign.client.config.{feignName}.url属性,可以对任何 Feign 客户端实例进行刷新。spring-doc.cadn.net.cn

你可以通过以下方式刷新这些属性POST /执行器/刷新.spring-doc.cadn.net.cn

默认情况下,Feign客户端的刷新行为是被禁用的。请使用以下属性来启用刷新行为:spring-doc.cadn.net.cn

spring.cloud.openfeign.client.refresh-enabled=true
不要对@FeignClient@RefreshScope注解。

OAuth2 支持

可以通过添加Spring-boot-starter-oAuth2-client对项目的依赖性以及设置以下flag:spring-doc.cadn.net.cn

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检索自网址将使用主持板块。spring-doc.cadn.net.cn

提示

使用服务ID作为 OAuth2 客户端 registrationId,对于负载均衡的 Feign 客户端来说非常方便。对于非负载均衡的,基于属性的clientRegistrationId(客户注册ID是一种合适的方法。spring-doc.cadn.net.cn

提示

如果你不想使用默认设置OAuth2AuthorizedClientManager你可以在配置中实例化这种类型的豆子。spring-doc.cadn.net.cn

转换负载均衡的HTTP请求

你可以使用选定的ServiceInstance以转换负载均衡的HTTP请求。spring-doc.cadn.net.cn

请求你需要实现并定义LoadBalancerFeignRequestTransformer如下:spring-doc.cadn.net.cn

@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以指定顺序。spring-doc.cadn.net.cn

X转发头部支持

转发主机X-转发-原始支持可通过设置以下标志来启用:spring-doc.cadn.net.cn

spring.cloud.loadbalancer.x-forwarded.enabled=true

支持为假客户端提供URL的方法

您可以通过以下任一方式为 Feign 客户端提供 URL:spring-doc.cadn.net.cn

示例

该网址在@FeignClient注解。spring-doc.cadn.net.cn

@FeignClient(name=“testClient”, url=“http://localhost:8081”)spring-doc.cadn.net.cn

该URL由网址注释的属性,无需负载均衡。spring-doc.cadn.net.cn

该网址在@FeignClient注释和 配置属性。spring-doc.cadn.net.cn

@FeignClient(name=“testClient”, url=“http://localhost:8081”)以及定义在application.ymlspring.cloud.openfeign.client.config.testClient.url=http://localhost:8081spring-doc.cadn.net.cn

该URL由网址注释的属性,无需负载均衡。 配置属性中提供的URL未被使用。spring-doc.cadn.net.cn

该网址未在@FeignClient但注释在配置属性中提供了。spring-doc.cadn.net.cn

@FeignClient(name=“testClient”)以及定义在application.ymlspring.cloud.openfeign.client.config.testClient.url=http://localhost:8081spring-doc.cadn.net.cn

URL通过配置属性解析,无需负载均衡。如果spring.cloud.openfeign.client.refresh-enabled=true然后,配置属性中定义的 URL 可以按照 Spring RefreshScope 支持中描述的进行刷新。spring-doc.cadn.net.cn

该URL也未在@FeignClient注释和配置属性中都没有。spring-doc.cadn.net.cn

@FeignClient(name=“testClient”)spring-doc.cadn.net.cn

该URL解析为名称标注属性,并实现负载均衡。spring-doc.cadn.net.cn

AOT与原生图像支持

Spring Cloud OpenFeign 支持 Spring AOT 变换和原生图片,但仅在关闭刷新模式、关闭 Feign 客户端刷新(默认设置)的情况下,懒惰@FeignClient属性解析禁用(默认设置)。spring-doc.cadn.net.cn

如果你想在AOT或原生图片模式下运行Spring Cloud OpenFeign客户端,请务必设置spring.cloud.refresh.enabledfalse.
如果你想在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 相关的配置属性列表,请查看附录页面spring-doc.cadn.net.cn