首页 > 解决方案 > How to set fixed headers to the feign client instead of setting on request level

问题描述

I am using feign client for inter-service communication; question is I am able to send the method/request headers on request level meaning ex:

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

But as header is fixed, instead of sending the same value to each request; can we set it on class level; I tried below; it is not working

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

Correct me with the API or an example.

标签: javaspring-bootfeign

解决方案


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

@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

推荐阅读