RestTemplate使用ClientHttpRequestInterceptor请求耗时不正确

记录RestTemplate的请求相关信息写了如下拦截器

    private ClientHttpRequestInterceptor logInterceptor() {
        return (request, body, execution) -> {
            StopWatch stopWatch = new StopWatch("request time");
            stopWatch.start();
            ClientHttpResponse response = execution.execute(request, body);
            stopWatch.stop();
            RestLog restLog = new RestLog();
            restLog.setMethod(request.getMethodValue());
            restLog.setUrl(request.getURI().toString());
            restLog.setCostTime(stopWatch.getTotalTimeMillis());
            if (canPrint(request.getHeaders())) {
                restLog.setReqBody(new String(body, StandardCharsets.UTF_8));
            }
            restLog.setReqContentType(request.getHeaders().getContentType());
            if (canPrint(response.getHeaders())) {
                restLog.setRespBody(IOUtils.toString(response.getBody(), StandardCharsets.UTF_8));
            }
            restLog.setRespContentType(response.getHeaders().getContentType());
            log.info(restLog);
            return response;
        };
    }

实际使用过程中发现即使请求时间很长,restLog的costTime依然只有0-2ms,这显然不科学,这里很容易联想到(假设你没有怀疑stopwatch有问题)

ClientHttpResponse response = execution.execute(request, body);

这一步是异步的,这里确实需要考虑响应式编程场景,所以改下stop的位置吧。

附上完整代码:

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.StopWatch;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.Duration;

/**
 * @author wxy
 * @version 1.0.0
 * @date 2023/4/11 16:39
 */
@ConditionalOnClass(RestTemplate.class)
@ConditionalOnMissingBean(RestTemplate.class)
public class RestTemplateSupport {

    private static final Log log = LogFactory.getLog("RestLogger");

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder, SpringBootProperties properties) {
        RestProperties rest = properties.getRest();
        return builder
                .requestFactory(() -> new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()))
                .setReadTimeout(Duration.ofMillis(rest.getReadTimeOut()))
                .setConnectTimeout(Duration.ofMillis(rest.getConnectTimeOut()))
                .additionalInterceptors(logInterceptor())
                .build();
    }

    private ClientHttpRequestInterceptor logInterceptor() {
        return (request, body, execution) -> {
            StopWatch stopWatch = new StopWatch("request time");
            stopWatch.start();
            ClientHttpResponse response = execution.execute(request, body);
            RestLog restLog = new RestLog();
            restLog.setMethod(request.getMethodValue());
            restLog.setUrl(request.getURI().toString());
            if (canPrint(request.getHeaders())) {
                restLog.setReqBody(new String(body, StandardCharsets.UTF_8));
            }
            restLog.setReqContentType(request.getHeaders().getContentType());
            if (canPrint(response.getHeaders())) {
                restLog.setRespBody(IOUtils.toString(response.getBody(), StandardCharsets.UTF_8));
            }
            restLog.setRespContentType(response.getHeaders().getContentType());
            stopWatch.stop();
            restLog.setCostTime(stopWatch.getTotalTimeMillis());
            log.info(restLog);
            return response;
        };
    }

    private static boolean canPrint(HttpHeaders headers) {
        MediaType contentType = headers.getContentType();
        return contentType != null &&
                (contentType.includes(MediaType.APPLICATION_JSON) || contentType.includes(MediaType.TEXT_PLAIN));
    }

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值