Spring - 如何在微服务之间自动传递http header

Spring - how to pass automatically http header between microservices

我有多个微服务

1. MangerApp 
2. ProcessApp
3. DoingStuffApp
4. .....

"MangerApp Microservices" 得到一个 Http-Request 我正在寻找一种自动传输某些 HTTP headers 的方法 在通话中,虽然我不想遍历每个地方并添加 Headers,但我的 HTTP header 存储为 thread-local 地图.

因为我打电话给其他 microservices,所以 RestTemplate 我有很多不同的电话 get/post/put/etc... 更改每一个并手动传递 header 效率不高。 我正在寻找一种方法来管理它,而不是现在扩展 RestTemplate Class

您可以使用 ClientHttpRequestInterceptor 来实现您所需要的。

1) 创建一个 HeaderInterceptor 实现 ClientHttpRequestInterceptor。在此示例中,它从 ThreadLocal 获取授权和接受 headers 并传播它们:

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 添加 header 拦截器:

restTemplate.getInterceptors().add(new HeaderInterceptor());