我有多个微服务
1. MangerApp
2. ProcessApp
3. DoingStuffApp
4. .....
“ MangerApp微服务”获得Http-Request
我正在寻找一种自动转移某些HTTP headers
的方法在通话中,虽然我不想遍历每个地方并做-添加标头,但我的HTTP
标头存储为thread-local Map。
自从我打给其他microservices
以来,在RestTemplate
上我有很多不同的电话,例如get/post/put/etc...
更改它们中的每个并手动传递标头效率不高。我正在寻找一种管理它的方法,除了现在扩展RestTemplate Class
。
您可以使用ClientHttpRequestInterceptor
实现所需的功能。
1]创建实现HeaderInterceptor
的ClientHttpRequestInterceptor
。在此示例中,它从ThreadLocal获取Authorization和Accept标头并将其传播:
public class HeaderInterceptor implements ClientHttpRequestInterceptor{
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
HttpHeaders headers = request.getHeaders();
List<String> authorization = HeaderThreadLocal.getAuthorization()
List<String> accept = HeaderThreadLocal.getAuthorization();
headers.addAll("Authorization", authorization);
headers.addAll("Accept", accept);
return execution.execute(request, body);
}
}
2)配置您的RestTemplate
bean,添加标头拦截器:
restTemplate.getInterceptors().add(new HeaderInterceptor());