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

问题描述 投票:0回答:1

我有多个微服务

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

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

自从我打给其他microservices以来,在RestTemplate上我有很多不同的电话,例如get/post/put/etc...更改它们中的每个并手动传递标头效率不高。我正在寻找一种管理它的方法,除了现在扩展RestTemplate Class

java spring rest restful-url spring-resttemplate
1个回答
1
投票

您可以使用ClientHttpRequestInterceptor实现所需的功能。

1]创建实现HeaderInterceptorClientHttpRequestInterceptor。在此示例中,它从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());
© www.soinside.com 2019 - 2024. All rights reserved.