【问题标题】:How to define global static header on Spring Boot Feign Client如何在 Spring Boot Feign Client 上定义全局静态标头
【发布时间】:2023-04-02 11:20:01
【问题描述】:

我有一个 Spring Boot 应用程序并想创建一个具有静态定义的标头值的 Feign 客户端(用于身份验证,但不是基本身份验证)。我找到了 @Headers 注释,但它似乎不适用于 Spring Boot 领域。我怀疑这与使用SpringMvcContract有关。

这是我想要工作的代码:

@FeignClient(name = "foo", url = "http://localhost:4444/feign")
@Headers({"myHeader:value"})
public interface LocalhostClient {

但它不添加标题。

我尝试制作了一个干净的 Spring Boot 应用,并在此处发布到 github:github example

我能够使其工作的唯一方法是将 RequestInterceptor 定义为全局 bean,但我不想这样做,因为它会影响其他客户端。

【问题讨论】:

    标签: spring-boot feign


    【解决方案1】:

    您也可以通过向各个方法添加标头来实现此目的,如下所示:

    @RequestMapping(method = RequestMethod.GET, path = "/resource", headers = {"myHeader=value"})
    

    Using @Headers with dynamic values in Feign client + Spring Cloud (Brixton RC2) 讨论了使用@RequestHeader 的动态值解决方案。

    【讨论】:

      【解决方案2】:

      您可以在您的 feign 接口上设置一个特定的配置类,并在其中定义一个 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
            }
          };
        }
      }
      

      【讨论】:

      • 谢谢!我对@Configuration 方法的唯一担心是 Feign 需要该注释,并且您必须小心将其排除在组件扫描之外。这对我来说似乎很危险。如果这个类以某种方式被添加到组件扫描中,突然间我们就会向我们所有的假端点发送敏感信息。 +1 虽然因为这在技术上回答了我的具体问题,即使我将使用阿里的建议
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 2018-02-01
      • 2021-03-15
      • 1970-01-01
      • 2017-03-29
      相关资源
      最近更新 更多