如何在 Spring Boot Feign Client 上定义全局静态 header
How to define global static header on Spring Boot Feign Client
我有一个 spring 引导应用程序,想创建一个具有静态定义的 header 值(用于身份验证,但不是基本身份验证)的 Feign 客户端。我找到了 @Headers
注释,但它似乎在 Spring Boot 领域不起作用。我怀疑这与使用 SpringMvcContract
.
有关
这是我要使用的代码:
@FeignClient(name = "foo", url = "http://localhost:4444/feign")
@Headers({"myHeader:value"})
public interface LocalhostClient {
但它不添加 headers。
我尝试制作了一个干净的 spring 启动应用程序并发布到 github 此处:github example
我能够让它工作的唯一方法是将 RequestInterceptor
定义为全局 bean,但我不想这样做,因为它会影响其他客户端。
您可以在您的 feign 接口上设置特定的配置 class 并在其中定义一个 RequestInterceptor bean。例如:
@FeignClient(name = "foo", url = "http://localhost:4444/feign",
configuration = FeignConfiguration.class)
public interface LocalhostClient {
}
@Configuration
public class FeignConfiguration {
@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
// Do what you want to do
}
};
}
}
您还可以通过向各个方法添加 header 来实现此目的,如下所示:
@RequestMapping(method = RequestMethod.GET, path = "/resource", headers = {"myHeader=value"})
Using @Headers with dynamic values in Feign client + Spring Cloud (Brixton RC2) 讨论了使用 @RequestHeader
.
的动态值解决方案
我有一个 spring 引导应用程序,想创建一个具有静态定义的 header 值(用于身份验证,但不是基本身份验证)的 Feign 客户端。我找到了 @Headers
注释,但它似乎在 Spring Boot 领域不起作用。我怀疑这与使用 SpringMvcContract
.
这是我要使用的代码:
@FeignClient(name = "foo", url = "http://localhost:4444/feign")
@Headers({"myHeader:value"})
public interface LocalhostClient {
但它不添加 headers。
我尝试制作了一个干净的 spring 启动应用程序并发布到 github 此处:github example
我能够让它工作的唯一方法是将 RequestInterceptor
定义为全局 bean,但我不想这样做,因为它会影响其他客户端。
您可以在您的 feign 接口上设置特定的配置 class 并在其中定义一个 RequestInterceptor bean。例如:
@FeignClient(name = "foo", url = "http://localhost:4444/feign",
configuration = FeignConfiguration.class)
public interface LocalhostClient {
}
@Configuration
public class FeignConfiguration {
@Bean
public RequestInterceptor requestTokenBearerInterceptor() {
return new RequestInterceptor() {
@Override
public void apply(RequestTemplate requestTemplate) {
// Do what you want to do
}
};
}
}
您还可以通过向各个方法添加 header 来实现此目的,如下所示:
@RequestMapping(method = RequestMethod.GET, path = "/resource", headers = {"myHeader=value"})
Using @Headers with dynamic values in Feign client + Spring Cloud (Brixton RC2) 讨论了使用 @RequestHeader
.