Cre*_*tor 1 java spring-boot feign
我正在使用 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);
Run Code Online (Sandbox Code Playgroud)
但由于 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);
Run Code Online (Sandbox Code Playgroud)
使用 API 或示例纠正我。
Vai*_*ibS 10
您可以创建一个拦截器,在所有请求中注入标头,如下所示:
@Bean
public RequestInterceptor requestInterceptor() {
return requestTemplate -> {
requestTemplate.header("user", username);
requestTemplate.header("password", password);
requestTemplate.header("Accept", ContentType.APPLICATION_JSON.getMimeType());
};
}
Run Code Online (Sandbox Code Playgroud)
它还提供了一种使用属性文件设置拦截器的方法,如下所示:
feign:
client:
config:
default:
requestInterceptors:
com.baeldung.cloud.openfeign.JSONPlaceHolderInterceptor
Run Code Online (Sandbox Code Playgroud)
我们可以创建默认的配置作为客户端名称来配置所有@FeignClient对象,或者我们可以为配置声明feign客户端名称
参考: https: //www.baeldung.com/spring-cloud-openfeign
编辑:另一种方法是在 yml 中设置标题,如下所示:
feign:
client:
config:
default:
defaultRequestHeaders:
Authorization:
- Basic dXNlcjpwYXNzd29yZA==
SomeOtherHeader:
- Value1
- Value2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14794 次 |
| 最近记录: |