测量Spring RestTemplate HTTP请求时间

whl*_*hlk 6 java performance spring web-services http

我想测量一个RestTemplate.getForObject调用的HTTP GET请求的时间,而没有解析响应所需的时间.所以只是远程HTTP调用所需的时间.我已经尝试过设置ClientHttpRequestInterceptor但是我不认为这是正确的方法,因为时间似乎是错误的:

public class PerfRequestSyncInterceptor implements ClientHttpRequestInterceptor {
private Logger log = Logger.getLogger(this.getClass());

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

    long start = System.nanoTime();
    ClientHttpResponse resp = execution.execute(request, body);

    log.debug("remote request time: "
            + ((System.nanoTime() - start) * Math.pow(10, -9)));
    return resp;
  }
}
Run Code Online (Sandbox Code Playgroud)


呼叫:

RestTemplate rest = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new PerfRequestSyncInterceptor());
rest.setInterceptors(interceptors);

Response inob = rest.getForObject(xmlURL, Response.class);
Run Code Online (Sandbox Code Playgroud)

如何衡量RestTemplate HTTP请求的时间?

Pet*_*nto 4

您可以使用AOP和Spring内置的PerformanceMonitorInterceptor。您需要正确定义要拦截哪个调用的哪些方法,然后才能进行测量。你可以像这样配置它:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans      
        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
        http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
    <bean id="springMonitoredService"
        class="com.myorg.service.springmon.MyServiceSpringImpl"/>


    <bean id="springMonitoringAspectInterceptor"        
class="org.springframework.aop.interceptor.PerformanceMonitorInterceptor">
        <property name="loggerName"     
                value="com.myorg.SPRING_MONITOR"/>      
    </bean>


    <aop:config>
            <aop:pointcut id="springMonitoringPointcut"
                   expression="execution(* java.net.HttpURLConnection.connect(..))"/>




                <aop:advisor pointcut-ref="springMonitoringPointcut" 
            advice-ref="springMonitoringAspectInterceptor"/>      
    </aop:config>

</beans>
Run Code Online (Sandbox Code Playgroud)