0%

restTemplate拦截器ClientHttpRequestInterceptor

restTemplate拦截器ClientHttpRequestInterceptor

restTemplate提供了一个拦截器链来对请求和响应做一些定制化的操作,只需要实现ClientHttpRequestInterceptor接口中的intercept方法

如添加请求头等操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {


@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {

this.traceRequest((ClientHttpRequest) request, body);
ClientHttpResponse response = execution.execute(request, body);
return response;
}

private void traceRequest(ClientHttpRequest request, byte[] body) throws UnsupportedEncodingException {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return;
}
HttpServletRequest req = ((ServletRequestAttributes) requestAttributes).getRequest();
HttpHeaders headers = new HttpHeaders();

String globalTraceId = req.getHeader("global-trace-id");
if (globalTraceId == null) {
headers.add("global-trace-id", TraceThreadLocal.getGlobalTraceId());
} else {
headers.add("global-trace-id", globalTraceId);
}
String parentTraceId = req.getHeader("local-trace-id");
if (parentTraceId == null) {
headers.add("parent-trace-id", TraceThreadLocal.getLocalTraceId());
} else {
headers.add("parent-trace-id", parentTraceId);
}
request.getHeaders().putAll(headers);
}


}

然后配置RestTemplate的时候将拦截器添加进去

1
2
3
4
5
6
7
8
9
10
@Bean
@ConditionalOnMissingBean
public RestTemplateInterceptor restTemplateInterceptor(RestTemplate restTemplate) {
RestTemplateInterceptor restTemplateInterceptor = new RestTemplateInterceptor();
List<ClientHttpRequestInterceptor> list = new ArrayList<>(
restTemplate.getInterceptors());
list.add(restTemplateInterceptor);
restTemplate.setInterceptors(list);
return restTemplateInterceptor;
}

欢迎关注我的其它发布渠道