Spring RestTemplate---ClientHttpRequestInterceptor

时间:2019-06-16 13:08:21   收藏:0   阅读:1235

Spring 应用中,经常使用Spring RestTemplate作为客户端向服务端发送Restful请求,如果每次请求都需要在http Header中添加相同的信息,可以通过ClientHttpRequestInterceptor来进行实现。

public class UserContextInterceptor implements ClientHttpRequestInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(UserContextInterceptor.class);
    @Override
    public ClientHttpResponse intercept(
            HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {

        HttpHeaders headers = request.getHeaders();
        headers.add(UserContext.CORRELATION_ID, UserContextHolder.getContext().getCorrelationId());
        headers.add(UserContext.AUTH_TOKEN, UserContextHolder.getContext().getAuthToken());

        return execution.execute(request, body);
    }
}

分布式调用中,可以通过RestTemplate的调用链路中添加关联ID,以便追踪执行链。

原文:https://www.cnblogs.com/lemondada/p/11030941.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!