【问题标题】:How to set fixed headers to the feign client instead of setting on request level如何为假装客户端设置固定标头而不是在请求级别设置
【发布时间】:2021-04-30 13:26:59
【问题描述】:

我正在使用 feign 客户端进行服务间通信;问题是我能够在请求级别发送方法/请求标头,例如:

@FeignClient(name = "product-service", url = "https://jsonplaceholder.typicode.com/")
public interface ProductClient {

    @GetMapping("/posts")
    List<PostDTO> fetchPosts(@RequestHeaders....);

    @GetMapping("/posts/{id}")
    List<PostDTO> fetchPostsById(@RequestHeaders...., @PathVariable("id")int id);

但是由于 header 是固定的,而不是向每个请求发送相同的值;我们可以在课堂上设置它吗?我在下面尝试过;它不工作

@FeignClient(name = "product-service", url = "https://jsonplaceholder.typicode.com/")
@Headers({
        "X-Ping: {token}"
})
public interface ProductClient {

    @GetMapping("/posts")
    List<PostDTO> fetchPosts(@RequestHeaders....);

    @GetMapping("/posts/{id}")
    List<PostDTO> fetchPostsById(@RequestHeaders...., @PathVariable("id")int id);

通过 API 或示例更正我。

【问题讨论】:

    标签: java spring-boot feign


    【解决方案1】:

    您可以创建一个在所有请求中注入标头的拦截器,如下所示:

    @Bean
    public RequestInterceptor requestInterceptor() {
      return requestTemplate -> {
          requestTemplate.header("user", username);
          requestTemplate.header("password", password);
          requestTemplate.header("Accept", ContentType.APPLICATION_JSON.getMimeType());
      };
    }
    

    它还提供了一种使用属性文件设置拦截器的方法,如下所示:

    feign:
      client:
        config:
          default:
            requestInterceptors:
              com.baeldung.cloud.openfeign.JSONPlaceHolderInterceptor
    

    我们可以创建配置默认为客户端名称来配置所有@FeignClient对象,或者我们可以声明一个配置的feign客户端名称

    参考:https://www.baeldung.com/spring-cloud-openfeign

    编辑: 另一种方法是在 yml 中设置标题,如下所示:

    feign:
      client:
        config:
          default:
            defaultRequestHeaders:
              Authorization:
                - Basic dXNlcjpwYXNzd29yZA==
              SomeOtherHeader:
                - Value1
                - Value2
    

    【讨论】:

      【解决方案2】:

      我们在下面使用了 kotlin 以确保我们为所有发送的请求添加正确的标头:

      带有配置设置的Feign客户端

      @FeignClient(name = "YourClient", url = "\${base-url}", configuration = [FeignHeaderConfiguration::class])
      interface YourClient 
      

      头文件配置

      @Configuration
      class FeignHeaderConfiguration {
      
          @Bean
          fun clientHeaderInterceptor(): ClientHeaderInterceptor {
              return ClientHeaderInterceptor()
          }
      }
      

      以及我们添加标头的拦截器

      class ClientHeaderInterceptor : RequestInterceptor {
          override fun apply(requestTemplate: RequestTemplate) {
             requestTemplate.header("Accept", MediaType.APPLICATION_JSON_VALUE)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-09-14
        • 1970-01-01
        • 1970-01-01
        • 2020-06-01
        • 1970-01-01
        • 2012-03-18
        • 2013-09-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多