首页 > 其他分享 >Spring Cloud OpenFeign

Spring Cloud OpenFeign

时间:2022-12-02 12:08:13浏览次数:32  
标签:FeignClient feign OpenFeign Spring enabled Feign Cloud 客户端

Spring Cloud OpenFeign_Cloud

该项目通过自动配置为 Spring Boot 应用程序提供 OpenFeign 集成 并绑定到 Spring 环境和其他 Spring 编程模型习语。

1. 声明式 REST 客户端:假装

Feign是一个声明式 Web 服务客户端。 它使编写 Web 服务客户端变得更加容易。 要使用Feign创建一个接口并对其进行注释。 它具有可插拔的注释支持,包括Feign注释和JAX-RS注释。 Feign还支持可插拔编码器和解码器。 Spring Cloud 增加了对 Spring MVC 注释的支持,并支持在 Spring Web 中默认使用相同注释。 Spring Cloud 集成了 Eureka、Spring Cloud Breaker 以及 Spring Cloud LoadBalancer,以便在使用 Feign 时提供负载平衡的 http 客户端。HttpMessageConverters

1.1. 如何包含假装

要将 Feign 包含在项目中,请使用带有组和工件 ID 的初学者。有关使用当前 Spring 云发布系列设置构建系统的详细信息,请参阅Spring 云项目页面。​​org.springframework.cloud​​​​spring-cloud-starter-openfeign​

示例弹簧启动应用

@SpringBootApplication
@EnableFeignClients
public class Application {

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

}

商店客户端.java

@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);
}

在注释中,字符串值(上面的“stores”)是一个任意的客户端名称,用于创建Spring Cloud LoadBalancer客户端。 您还可以使用属性指定 URL (绝对值或只是一个主机名)。豆子在 应用程序上下文是接口的完全限定名称。 要指定您自己的别名值,您可以使用该值 的注释。@FeignClienturlqualifiers@FeignClient

上面的负载均衡器客户端需要发现物理地址 对于“商店”服务。如果您的应用程序是 Eureka 客户端,则 它将解析 Eureka 服务注册表中的服务。如果你 不想使用尤里卡,可以配置服务器列表 在外部配置中使用简单发现客户端。

Spring Cloud OpenFeign支持Spring Cloud LoadBalancer阻塞模式可用的所有功能。您可以在项目文档中阅读有关它们的更多信息。

要使用注释类,请确保指定客户端所在的位置,例如:或显式列出它们:​​@EnableFeignClients​​​​@Configuration​​​​@EnableFeignClients(basePackages = "com.example.clients")​​​​@EnableFeignClients(clients = InventoryServiceFeignClient.class)​

1.2. 覆盖假装默认值

Spring Cloud 的 Feign 支持中的核心概念是指定客户端的概念。每个假装客户端都是组件集合的一部分,这些组件协同工作以按需联系远程服务器,并且集合有一个名称,您作为应用程序开发人员使用注释为其指定。Spring Cloud 为每个命名客户端创建一个新的融合作为匿名需求。它包含(除其他事项外)an、a 和 a。 可以使用注释的属性来覆盖该融合的名称。​​@FeignClient​​​​ApplicationContext​​​​FeignClientsConfiguration​​​​feign.Decoder​​​​feign.Encoder​​​​feign.Contract​​​​contextId​​​​@FeignClient​

Spring Cloud 允许您通过使用声明其他配置(在顶部)来完全控制假客户端。例:​​FeignClientsConfiguration​​​​@FeignClient​

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

在这种情况下,客户端由已经与任何 in(后者将覆盖前者)的组件组成。​​FeignClientsConfiguration​​​​FooConfiguration​

​FooConfiguration​​​不需要注释。但是,如果是,则请注意将其从任何包含此配置的内容中排除,因为它将成为默认源,,,等,当指定时。这可以通过将它放在与 anyor 分开的、不重叠的包中来避免,或者可以显式排除它。​​@Configuration​​​​@ComponentScan​​​​feign.Decoder​​​​feign.Encoder​​​​feign.Contract​​​​@ComponentScan​​​​@SpringBootApplication​​​​@ComponentScan​

使用注释的属性,除了更改名称 集合,它将覆盖客户端名称的别名 它将用作为该客户机创建的配置 Bean 名称的一部分。​​contextId​​​​@FeignClient​​​​ApplicationContext​

以前,使用属性,不需要属性。使用是现在必需的。​​url​​​​name​​​​name​

占位符在属性中受支持。​​name​​​​url​

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

Spring Cloud OpenFeign 默认为 feign 提供以下 bean(beanName:):​​BeanType​​​​ClassName​

  • ​Decoder​​feignDecoder:(它包装了一个ResponseEntityDecoderSpringDecoder)
  • ​Encoder​​feignEncoder:SpringEncoder
  • ​Logger​​feignLogger:Slf4jLogger
  • ​MicrometerCapability​​千分尺功能:类路径上的 Ifis 并且可用feign-micrometerMeterRegistry
  • ​CachingCapability​​缓存功能:使用Ifannotation。可以通过以下方式禁用。@EnableCachingfeign.cache.enabled
  • ​Contract​​假装合约:SpringMvcContract
  • ​Feign.Builder​​feignBuilder:FeignCircuitBreaker.Builder
  • ​Client​​feignClient:如果 Spring Cloud LoadBalancer 在类路径上,则使用。 如果类路径上没有它们,则使用缺省假装客户端。FeignBlockingLoadBalancerClient

​spring-cloud-starter-openfeign​​​支持。但是,由于是可选的依赖项,如果要使用它,则需要确保它已添加到项目中。​​spring-cloud-starter-loadbalancer​

OkHttpClient 和 ApacheHttpClient 和 ApacheHC5 假装客户端可以分别由 setororto 使用,并将它们放在类路径上。 您可以通过提供 bean 来自定义使用的 HTTP 客户端,当使用 Apache 或使用 OK HTTP 或使用 Apache HC5 时。​​feign.okhttp.enabled​​​​feign.httpclient.enabled​​​​feign.httpclient.hc5.enabled​​​​true​​​​org.apache.http.impl.client.CloseableHttpClient​​​​okhttp3.OkHttpClient​​​​org.apache.hc.client5.http.impl.classic.CloseableHttpClient​

Spring Cloud OpenFeign默认不提供以下 bean 用于 feign,但仍会从应用程序上下文中查找这些类型的 bean 来创建 feign 客户端:

  • ​Logger.Level​
  • ​Retryer​
  • ​ErrorDecoder​
  • ​Request.Options​
  • ​Collection<RequestInterceptor>​
  • ​SetterFactory​
  • ​QueryMapEncoder​
  • ​Capability​​ (MicrometerCapability默认提供)CachingCapability

默认情况下会创建具有该类型的 bean,这将禁用重试。 请注意,此重试行为与 Feign 默认行为不同,后者将自动重试 IOExceptions, 将它们视为与网络相关的暂时性异常,以及从错误解码器引发的任何可重试异常。​​Retryer.NEVER_RETRY​​​​Retryer​

创建其中一种类型的 bean 并将其放置在 aconfig(如上面)中,允许您覆盖所描述的每个 bean。例:​​@FeignClient​​​​FooConfiguration​

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

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

这替换了 thewith,并添加了 ato 的集合。​​SpringMvcContract​​​​feign.Contract.Default​​​​RequestInterceptor​​​​RequestInterceptor​

​@FeignClient​​也可以使用配置属性进行配置。

应用程序.yml

feign:
client:
config:
feignName:
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
decode404: false
encoder: com.example.SimpleEncoder
decoder: com.example.SimpleDecoder
contract: com.example.SimpleContract
capabilities:
- com.example.FooCapability
- com.example.BarCapability
queryMapEncoder: com.example.SimpleQueryMapEncoder
metrics.enabled: false

默认配置可以在属性中以类似于上述的方式指定。不同之处在于此配置将应用于所有假客户端。​​@EnableFeignClients​​​​defaultConfiguration​

如果您希望使用配置属性来配置所有属性,则可以使用假装名称创建配置属性。​​@FeignClient​​​​default​

您可以使用 and 指定查询参数和标头,这些参数和标头将与命名的客户端的每个请求一起发送。​​feign.client.config.feignName.defaultQueryParameters​​​​feign.client.config.feignName.defaultRequestHeaders​​​​feignName​

应用程序.yml

feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
loggerLevel: basic

如果我们同时创建 Bean 和配置属性,则配置属性将获胜。 它将覆盖值。但是,如果要将优先级更改为, 你可以换成。​​@Configuration​​​​@Configuration​​​​@Configuration​​​​feign.client.default-to-properties​​​​false​

如果我们想创建多个具有相同名称或 url 的假客户端 这样它们就会指向同一台服务器,但每个服务器都有不同的自定义配置 我们必须使用属性的为了避免名称 这些配置豆的冲突。​​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 配置为不从父上下文继承 bean。 您可以通过覆盖 abean 返回来执行此操作:​​inheritParentConfiguration()​​​​FeignClientConfigurer​​​​false​

@Configuration
public class CustomConfiguration{

@Bean
public FeignClientConfigurer feignClientConfigurer() {
return new FeignClientConfigurer() {

@Override
public boolean inheritParentConfiguration() {
return false;
}
};

}
}

默认情况下,Feign 客户端不对斜杠字符进行编码。您可以通过设置 ofto 值来更改此行为。​​/​​​​feign.client.decodeSlash​​​​false​

1.2.1.弹簧编码器配置

在我们提供的中,我们为二进制内容类型和所有其他内容类型设置了字符集。​​SpringEncoder​​​​null​​​​UTF-8​

您可以修改此行为以通过设置 ofto 值从标头字符集派生字符集。​​Content-Type​​​​feign.encoder.charset-from-content-type​​​​true​

1.3. 超时处理

我们可以在默认客户端和命名客户端上配置超时。OpenFeign 使用两个超时参数:

  • ​connectTimeout​​防止由于服务器处理时间过长而阻止调用方。
  • ​readTimeout​​从建立连接时开始应用,并在返回响应时间过长时触发。

如果服务器未运行或不可用,则数据包会导致连接被拒绝。通信以错误消息或回退结束。这可能发生在之前,如果它被设置得很低。执行查找和接收此类数据包所花费的时间会导致此延迟的很大一部分。它可能会根据涉及 DNS 查找的远程主机而更改。​​connectTimeout​

1.4. 手动创建假客户端

在某些情况下,可能需要以不 可以使用上述方法。在这种情况下,您可以使用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, MicrometerCapability micrometerCapability) {
this.fooClient = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.addCapability(micrometerCapability)
.requestInterceptor(new BasicAuthRequestInterceptor("user", "user"))
.target(FooClient.class, "https://PROD-SVC");

this.adminClient = Feign.builder().client(client)
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.addCapability(micrometerCapability)
.requestInterceptor(new BasicAuthRequestInterceptor("admin", "admin"))
.target(FooClient.class, "https://PROD-SVC");
}
}

在上面的例子是默认配置 由Spring Cloud OpenFeign提供。​​FeignClientsConfiguration.class​

​PROD-SVC​​是客户端将向其发出请求的服务的名称。

Feignobject 定义哪些注释和值在接口上有效。这 autowiredbean 提供对 SpringMVC 注释的支持,而不是 默认的假本机批注。​​Contract​​​​Contract​

你也可以使用theon。​​Builder`to configure FeignClient not to inherit beans from the parent context. You can do this by overriding calling `inheritParentContext(false)​​​​Builder​

1.5. 假弹簧云断路器支持

如果 Spring Cloud Breaker 位于类路径上,Feign 将使用断路器包装所有方法。​​feign.circuitbreaker.enabled=true​

要按客户端禁用 Spring Cloud Breaker 支持,请创建一个具有“原型”范围的香草,例如:​​Feign.Builder​

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

断路器名称遵循此模式。当调用awithinterface和没有参数的被调用接口方法时,断路器名称将是。​​<feignClientClassName>#<calledMethod>(<parameterTypes>)​​​​@FeignClient​​​​FooClient​​​​bar​​​​FooClient#bar()​

自 2020.0.2 起,断路器名称模式已从 更改。 使用2020.0.4中引入的断路器名称可以保留旧模式。​​<feignClientName>_<calledMethod>​​​​CircuitBreakerNameResolver​

提供 bean,您可以更改断路器名称模式。​​CircuitBreakerNameResolver​

@Configuration
public class FooConfiguration {
@Bean
public CircuitBreakerNameResolver circuitBreakerNameResolver() {
return (String feignClientName, Target<?> target, Method method) -> feignClientName + "_" + method.getName();
}
}

要启用 Spring Cloud Breaker 组,请将属性设置为 (默认情况下)。​​feign.circuitbreaker.group.enabled​​​​true​​​​false​

1.6. 使用配置属性配置断路器

您可以通过配置属性配置断路器。要做setto。因为 您不能在我们需要的配置属性名称中使用诸如,,之类的字符 更改 OpenFeign 生成的断路器 ID 的命名约定。以上 酒店将为您执行此操作。​​feign.circuitbreaker.alphanumeric-ids.enabled​​​​true​​​​#​​​​(​​​​)​​​​,​

例如,如果你有这个Feign客户端

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

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

您可以通过执行以下操作来使用配置属性对其进行配置

feign:
circuitbreaker:
enabled: true
alphanumeric-ids:
enabled: true
resilience4j:
circuitbreaker:
instances:
DemoClientgetDemo:
minimumNumberOfCalls: 69
timelimiter:
instances:
DemoClientgetDemo:
timeoutDuration: 10s

1.7. 假弹簧云断路器回退

Spring Cloud Breaker支持回退的概念:电路打开或出现错误时执行的默认代码路径。为给定集启用回退,该属性到实现回退的类名。您还需要将您的实现声明为 Spring bean。​​@FeignClient​​​​fallback​

@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";
}

}

如果需要访问进行回退触发器的原因,则可以在内部使用该属性。​​fallbackFactory​​​​@FeignClient​

@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. 假装和@Primary

当将 Feign 与 Spring Cloud Breaker 回退一起使用时,同一类型中有多个 bean。这将导致不起作用,因为没有一个 bean,或者一个标记为主 bean。为了解决这个问题,Spring Cloud OpenFeign 将所有 Feign 实例标记为,因此 Spring Framework 将知道要注入哪个 bean。在某些情况下,这可能不可取。要关闭此行为,请将属性 of 设置为 false。​​ApplicationContext​​​​@Autowired​​​​@Primary​​​​primary​​​​@FeignClient​

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

1.9. 假继承支持

Feign 通过单继承接口支持样板 API。 这允许将常见操作分组到方便的基本接口中。

用户服务.java

public interface UserService {

@RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
User getUser(@PathVariable("id") long id);
}

用户资源.java

@RestController
public class UserResource implements UserService {

}

用户客户端.java

package project.user;

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

}

​@FeignClient​​​不应在服务器和客户端之间共享接口,并且不再支持在类级别上注释接口。​​@FeignClient​​​​@RequestMapping​

1.10. 假请求/响应压缩

您可以考虑为您的启用请求或响应 GZIP 压缩 佯装请求。您可以通过启用以下属性之一来执行此操作:

feign.compression.request.enabled=true
feign.compression.response.enabled=true

假请求压缩为您提供的设置类似于您可能为 Web 服务器设置的设置:

feign.compression.request.enabled=true
feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=2048

这些属性允许您选择压缩媒体类型和最小请求阈值长度。

1.11. 假装日志记录

为每个创建的 Feign 客户端创建一个记录器。默认情况下,记录器的名称是用于创建 Feign 客户端的接口的完整类名。假装日志记录仅响应级别。​​DEBUG​

应用程序.yml

logging.level.project.user.UserClient: DEBUG

您可以为每个客户端配置的对象告诉 Feign 要记录多少。选择是:​​Logger.Level​

  • ​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​

创建一个或多个 Bean 并将它们放置在配置中,可以注册它们并修改相关客户端的行为。​​Capability​​​​@FeignClient​

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

1.13. 假指标

如果满足以下所有条件,则会创建并注册 abean,以便您的 Feign 客户端将指标发布到 Micrometer:​​MicrometerCapability​

  • ​feign-micrometer​​位于类路径上
  • 阿豆可用MeterRegistry
  • 假装指标属性设置为(默认情况下)true
  • ​feign.metrics.enabled=true​​(适用于所有客户)
  • ​feign.client.config.feignName.metrics.enabled=true​​(对于单个客户端)

如果您的应用程序已经使用 Micrometer,则启用指标就像放入类路径一样简单。​​feign-micrometer​

您还可以通过以下任一方式禁用该功能:

  • 从类路径中排除feign-micrometer
  • 将其中一个假装指标属性设置为false
  • ​feign.metrics.enabled=false​
  • ​feign.client.config.feignName.metrics.enabled=false​

​feign.metrics.enabled=false​​禁用对所有Feign 客户端的指标支持,而不考虑客户端级标志的值:。 如果要启用或禁用每个客户端的 merics,请不要设置和使用。​​feign.client.config.feignName.metrics.enabled​​​​feign.metrics.enabled​​​​feign.client.config.feignName.metrics.enabled​

您还可以通过注册自己的 bean 进行自定义:​​MicrometerCapability​

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

1.14. 假缓存

使用 Ifannotation,创建并注册 abean,以便您的 Feign 客户端在其接口上识别sannotations:​​@EnableCaching​​​​CachingCapability​​​​@Cache*​

public interface DemoClient {

@GetMapping("/demo/{filterParam}")
@Cacheable(cacheNames = "demo-cache", key = "#keyParam")
String demoEndpoint(String keyParam, @PathVariable String filterParam);
}

您也可以通过属性禁用该功能。​​feign.cache.enabled=false​

1.15. 假装@QueryMap支持

OpenFeignannotation 为 POJO 提供了对用作 GET 参数映射。不幸的是,默认的OpenFeign QueryMap注释是 与春天不兼容,因为它缺乏属性。​​@QueryMap​​​​value​

Spring Cloud OpenFeign 提供了一个等效的注释,它 用于将 POJO 或 Map 参数注释为查询参数映射。​​@SpringQueryMap​

例如,类定义参数和:​​Params​​​​param1​​​​param2​

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

// [Getters and setters omitted for brevity]
}

以下假装客户端通过使用注释来使用类:​​Params​​​​@SpringQueryMap​

@FeignClient("demo")
public interface DemoTemplate {

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

如果需要对生成的查询参数映射进行更多控制,则可以实现自定义 Bean。​​QueryMapEncoder​

1.16. 哈特亚斯支持

Spring 提供了一些 API 来创建遵循HATEOAS原则、Spring Hateoas和Spring Data REST 的 REST 表示。

如果您的项目使用入门器 或启动器,默认情况下启用 Feign HATEOAS 支持。​​org.springframework.boot:spring-boot-starter-hateoas​​​​org.springframework.boot:spring-boot-starter-data-rest​

启用 HATEOAS 支持后,允许 Feign 客户端序列化 并反序列化 HATEOAS 表示模型:实体模型、集合模型和分页模型。

@FeignClient("demo")
public interface DemoTemplate {

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

1.17. 春季@MatrixVariable支持

Spring Cloud OpenFeign 为 Springannotation 提供支持。​​@MatrixVariable​

如果将映射作为方法参数传递,则通过将映射中的键值对与 a 联接来创建路径段。​​@MatrixVariable​​​​=​

如果传递了不同的对象,则在注释中提供(如果已定义)或注释的变量名称为 使用提供的方法参数连接。​​name​​​​@MatrixVariable​​​​=​

重要

尽管在服务器端,Spring 不要求用户将路径段占位符命名为与矩阵变量名称相同的名称,因为它在客户端过于模糊,Spring Cloud OpenFeign 要求您添加一个路径段占位符,其名称与注释中提供的名称(如果已定义)或注释变量名称相匹配。​​name​​​​@MatrixVariable​

例如:

@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. 假装集合格式支持

我们通过提供注释来支持。 您可以通过传递 desiredas 注释值来注释 Feign 客户端方法(或影响所有方法的整个类)。​​feign.CollectionFormat​​​​@CollectionFormat​​​​feign.CollectionFormat​

在下面的示例中,使用 format,而不是 defaultto 处理该方法。​​CSV​​​​EXPLODED​

@FeignClient(name = "demo")
protected interface PageableFeignClient {

@CollectionFormat(feign.CollectionFormat.CSV)
@GetMapping(path = "/page")
ResponseEntity performRequest(Pageable page);

}

设置格式发送时作为查询参数,以便正确编码。​​CSV​​​​Pageable​

1.19. 反应式支持

由于OpenFeign 项目目前不支持响应式客户端,例如 SpringWebClient,Spring Cloud OpenFeign 也不支持。

在此之前,我们建议对Spring WebClient支持使用feign-reactive。

1.19.1. 早期初始化错误

根据您使用 Feign 客户端的方式,您可能会在启动应用程序时看到初始化错误。 要变通解决此问题,您可以使用 anwhen 自动连接客户端。​​ObjectProvider​

@Autowired
ObjectProvider<TestFeignClient> testFeignClient;

1.20. 弹簧数据支持

您可以考虑启用杰克逊模块的支持和解码。​​org.springframework.data.domain.Page​​​​org.springframework.data.domain.Sort​

feign.autoconfiguration.jackson.enabled=true

1.21. 弹簧@RefreshScope支持

如果启用了 Feign 客户机刷新,那么将使用刷新范围的 Bean 创建每个假客户机。这意味着可以通过任何 Feign 客户端实例刷新诸如 andand 之类的属性。​​feign.Request.Options​​​​connectTimeout​​​​readTimeout​​​​POST /actuator/refresh​

默认情况下,Feign 客户端中的刷新行为处于禁用状态。使用以下属性启用刷新行为:

feign.client.refresh-enabled=true

不要用注释注释界面。​​@FeignClient​​​​@RefreshScope​

1.22. OAuth2 支持

可以通过设置以下标志来启用 OAuth2 支持:

feign.oauth2.enabled=true

1.22.1. 已弃用的 OAuth2 支持

当标志设置为 and,并且存在于类路径和 oauth2 客户端上下文资源详细信息中,并且存在 andbean,则会创建类的 Bean。在每个请求之前,侦听器会解析所需的访问令牌并将其作为标头包含在内。 有时,当为 Feign 客户端启用负载均衡时,您可能还希望使用负载均衡来获取访问令牌。为此,您应该确保负载平衡器位于类路径(spring-cloud-starter-load balancer)上,并通过设置以下标志为 OAuth2FeignRequestInterceptor 显式启用负载平衡:​​true​​​​spring-security-oauth2-autoconfigure​​​​OAuth2ClientContext​​​​OAuth2ProtectedResourceDetails​​​​OAuth2FeignRequestInterceptor​

feign.oauth2.load-balanced=true

警告

如上所述的 OAuth2 支持现已弃用,因为已达到生命周期的终点。请改用下面描述的模式。​​spring-security-oauth2-autoconfigure​

1.22.2. 当前对 OAuth2 的支持

当标志设置为 true 时,并且存在于类路径中,则创建类的 bean。在每个请求之前,拦截器解析所需的访问令牌并将其作为标头包含在内。use theto getThat 持有一个。如果用户指定了 OAuth2using 属性,它将用于检索令牌。如果未检索令牌或尚未指定令牌,则将使用从主机段检索的令牌。​​feign.client.refresh-enabled​​​​spring-security-oauth2-client​​​​OAuth2AccessTokenInterceptor​​​​OAuth2AccessTokenInterceptor​​​​OAuth2AuthorizedClientManager​​​​OAuth2AuthorizedClient​​​​OAuth2AccessToken​​​​clientRegistrationId​​​​feign.oauth2.clientRegistrationId​​​​clientRegistrationId​​​​serviceId​​​​url​

提示

使用 OAuth2 客户端注册 ID 对于负载平衡的 Feign 客户端来说很方便。对于非负载平衡的,基于属性是一种合适的方法。​​serviceId​​​​clientRegistrationId​

提示

如果您不想使用 的默认设置,您可以在配置中实例化这种类型的 Bean。​​OAuth2AuthorizedClientManager​

1.23. 转换负载均衡的 HTTP 请求

您可以使用 selected来转换负载平衡的 HTTP 请求。​​ServiceInstance​

为此,您需要实现和定义,如下所示:​​Request​​​​LoadBalancerFeignRequestTransformer​

== Configuration properties

To see the list of all Spring Cloud OpenFeign related configuration properties please check link:appendix.html[the Appendix page].

标签:FeignClient,feign,OpenFeign,Spring,enabled,Feign,Cloud,客户端
From: https://blog.51cto.com/u_15326439/5906853

相关文章

  • 代码讲解spring中的singleton和prototype
    1.singleton配置中的bean定义可以看作是一个模板,容器会根据这个模板来构造对象。bean定义中的scope语义会决定:容器将根据这个模板构造多少对象实例,......
  • CXF spring jaxws:endpoint jaxws:server 区别 与 关系
    First,theyareallfortheserversideconfiguration.Second,jaxws:endpointiscomingfromJAXWSAPI,anditisusedtoconfiguretheo......
  • springIOC和AOP
    IOC(InverseofControl:控制反转)是一种设计思想,就是将原本在程序中手动创建对象的控制权,交由Spring框架来管理。Ioc在其他语言中也有应用,并非spring特有。Ioc容器是Spring用......
  • spring mvc中普通类获得request
    springmvc中,在控制层很容易获得request,response,但在其他层的话获得的话,其实必要性不大,但可以实现:在web.xml中加入<listener><list......
  • springsecurity中处理框架页
    X-Frame-Options响应头X-Frame-OptionsHTTP响应头是用来给浏览器指示允许一个页面可否在<frame>,</iframe>或者<object>中展现的标记。网站可以使用此功能,来确保自......
  • spring+hibernate中用好DAO模版设置
     在spring+hibernate中,由于基于hibernatedaosupport的dao组件必须获得sessionfactory的引用,因此可以让所有的DAO组件继承一个DAO模版,在其中防止其......
  • spring boot替换jar包中引用的jar包(Unable to open nested entry 'BOOT-INF/lib/**.ja
    场景springboot项目,使用打jar包方式部署时,准备替换包中依赖时(不想重新打包),方法是使用压缩软件打开,直接复制替换掉相应依赖jar包,结果启动时报错Exceptioninthread"mai......
  • spring mvc下css js中的jsession id?
    在http://www.mkyong.com/spring-mvc/jsp-jsessionid-added-to-css-and-js-link/中提到了在springmvc+jsp中,对资源文件的引入问题,比如:<html><hea......
  • Spring security 3中关于方法级的权限限制
    Springsecurity3中关于方法级的权限控制有两个方法1)使用注解@PreAuthorize和@PostAuthorize,要先在配置文件中启用:<global-method-securityse......
  • (转)Spring中@Autowired注解、@Resource注解的区别
    Spring不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource、@PostConstruct以及@PreDestroy。@Resource的......