java - 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.
解决方案
您可以创建一个拦截器,在所有请求中注入标头,如下所示:
@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
推荐阅读
- reactjs - 如何在反应应用程序中全局捕获错误
- sql - 如何在具有有限选择的 Postgres 表中创建列
- angularjs - 在Angularjs中的指令之间传递回调
- amazon-web-services - AWS Cognito 用户池使用 Google Captcha 忘记密码
- elasticsearch - 如何让关键字映射在 NEST 中工作?
- c++ - 在包含的文件中抑制关于#pragma pack 的警告
- javascript - Vuex Mutation 正在运行,但组件在 vue 开发工具中手动提交之前不会更新
- python - 在 Python 中快速实现 N-Grams
- scala - 如何在scala中实现类似策略模式的东西
- python - 用scrapy抓取表格,网站有不寻常的html代码。