【问题标题】:Spring - how to pass automatically http header between microservicesSpring - 如何在微服务之间自动传递http标头
【发布时间】:2020-06-14 12:17:43
【问题描述】:

我有多个微服务

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

“MangerApp 微服务”获得Http-Request 我正在寻找一种方法来自动传输一些HTTP headers 在通话中,虽然我不想遍历每个地方并执行 - 添加标头,但我的 HTTP 标头存储为 thread-local Map

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

【问题讨论】:

    标签: java spring rest restful-url spring-resttemplate


    【解决方案1】:

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

    1) 创建一个实现ClientHttpRequestInterceptorHeaderInterceptor。在此示例中,它从 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());
    

    【讨论】:

    • 在这里阅读baeldung.com/spring-rest-template-interceptor,它表示它将拦截每个来电。 “每个传入的请求都会调用我们的拦截器”,我需要的是拦截每个传出的调用
    • 这就是这个实现的作用。 Baeldung 的文章展示了如何在响应中添加标头。我的代码为 RestTemplate 请求添加了它,这正是您所需要的。
    猜你喜欢
    • 2019-02-12
    • 2016-02-28
    • 2016-10-16
    • 2017-08-29
    • 2021-03-26
    • 1970-01-01
    • 2018-11-03
    • 2018-01-22
    • 2016-02-16
    相关资源
    最近更新 更多