[英]How to set fixed headers to the feign client instead of setting on request level
我正在使用 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 是固定的,而不是向每个请求发送相同的值; 我们可以将它设置在 class 级别吗? 我在下面尝试过; 它不工作
@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 或示例纠正我。
您可以创建一个拦截器,在所有请求中注入标头,如下所示:
@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
我们在下面使用了 kotlin 以确保我们为所有发送的请求添加正确的标头:
带有配置设置的 Feign 客户端
@FeignClient(name = "YourClient", url = "\${base-url}", configuration = [FeignHeaderConfiguration::class])
interface YourClient
Header配置
@Configuration
class FeignHeaderConfiguration {
@Bean
fun clientHeaderInterceptor(): ClientHeaderInterceptor {
return ClientHeaderInterceptor()
}
}
和拦截器,我们在其中添加了 header
class ClientHeaderInterceptor : RequestInterceptor {
override fun apply(requestTemplate: RequestTemplate) {
requestTemplate.header("Accept", MediaType.APPLICATION_JSON_VALUE)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.