Feign调用者如何配置全局Header参数?

作为Feign的调用者,如何配置一个全局的Header呢?

前言:

  • 因为项目遇到了这个问题,就是作为Feign 的调用者,应该如何传递认证信息,因为是新项目,所以刚开始开发没有考虑这些,之后才发现会有这个问题
  • 刚开始本来准备直接给每个Feign 方法添加一个用于认证的参数,但是发现这样改动量太大了,然后就开始查找资料
  • 功夫不负有心人,还真被我找到了,就是今天要介绍的Feign 中用于构建和修改HTTP请求的一个核心类RequestTemplate

在我项目中的使用

  • 创建一个FeignConfig的配置类,然后把下面的信息复制到类中即可
  • 因为我目前的项目中只是用于添加一个Header参数,所以用的比较简单,就只是下面的几行代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/
* feign全局处理器,自动添加header参数,无需手动传递租户信息
*
* @Author bo.chen
* @Date 2024/8/12
*/
@Configuration
public class FeignConfig {

@Bean
public RequestInterceptor requestInterceptor() {
return requestTemplate -> {
requestTemplate.header("tenantCode", "DEFAULT_GROUP");
};
}
}

作为Feign服务的提供者获取这个参数就比较简单了,使用SpringBoot的http请求的拦截器(HandlerInterceptorAdapter)即可获取到这个参数

RequestTemplate详细介绍

1. 路径和 URI 相关方法

  • 设置请求的 URI 路径。

    1
    requestTemplate.uri("/new-path");
  • 设置请求的方法(GET、POST、PUT 等)。

    1
    requestTemplate.method("POST");
  • 添加查询参数(URL 参数)。

    1
    requestTemplate.query("key", "value1", "value2");
  • 设置是否对 URL 中的斜杠进行解码。

    1
    requestTemplate.decodeSlash(false);
  • 使用传入的参数解析模板中的占位符。占位符的形式一般是 {name}

    1
    requestTemplate.resolve(new Object[]{"value"});
  • 设置请求的目标 URL,通常是基础 URL。

    1
    requestTemplate.target("http://example.com");

2. 请求头相关方法

  • 添加或设置请求头。

    1
    requestTemplate.header("Authorization", "Bearer token");
  • 获取当前请求头的 Map 结构。

    1
    Map<String, Collection<String>> headers = requestTemplate.headers();
  • 设置请求的字符集。

    1
    requestTemplate.requestCharset(StandardCharsets.UTF_8);

3. 请求体相关方法

  • 直接设置请求体的内容和字符集。

    1
    requestTemplate.body("your request body".getBytes(), StandardCharsets.UTF_8);
  • 以字符串形式设置请求体内容。

    1
    requestTemplate.body("your request body");
  • 使用模板字符串设置请求体,可以包括占位符,在 resolve 时替换。

    1
    requestTemplate.bodyTemplate("This is a body template with {param}");

4. 请求方法相关

  • 获取与当前模板关联的MethodMetadata ,其中包含有关方法的元信息。

    1
    MethodMetadata metadata = requestTemplate.methodMetadata();

5. 克隆和复制

  • 创建当前模板的副本。

    1
    RequestTemplate newTemplate = requestTemplate.clone();
  • 使用另一个RequestTemplate 替换当前模板的内容。

    1
    requestTemplate.replace(newTemplate);