测量Spring RestTemplate HTTP请求时间

时间:2012-11-08 10:04:01

标签: java performance web-services spring 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;
  }
}


呼叫:

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

Response inob = rest.getForObject(xmlURL, Response.class);

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

3 个答案:

答案 0 :(得分:4)

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

<?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>

答案 1 :(得分:2)

您可以使用秒表来完成此操作。

public class PerfRequestSyncInterceptor implements ClientHttpRequestInterceptor {

    private final static Logger LOG = LoggerFactory.getLogger(PerfRequestSyncInterceptor.class);

    @Override
    public ClientHttpResponse intercept(HttpRequest hr, byte[] bytes, ClientHttpRequestExecution chre) throws IOException {
        StopWatch stopwatch = StopWatch.createStarted();
        ClientHttpResponse response = chre.execute(hr, bytes);
        stopwatch.stop();

        LOG.info("method=" + hr.getMethod() + ", uri="+hr.getURI() + ", response_time=" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + ", response_code=" + response.getStatusCode().value());

        return response;
    }
}

在restTemplate实例化的类中

private final List<ClientHttpRequestInterceptor> requestInterceptors = new ArrayList<>();
requestInterceptors.add(new PerfRequestSyncInterceptor());
this.restTemplate.setInterceptors(requestInterceptors);

为maven添加秒表依赖项:

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>r05</version>
</dependency>

答案 2 :(得分:0)

  

我想测量a的HTTP GET请求的时间   RestTemplate.getForObject调用没有解析所需的时间   回应

我有同样的要求。我想知道服务器响应时间来衡量服务器在没有任何RestTemplate响应处理的情况下响应的时间。我使用地图向HttpClientBuilder添加了两个拦截器,以便我可以测量低级别请求和响应之间的时间。

HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

// Attach interceptors
ResponseTimeInterceptor interceptor = new ResponseTimeInterceptor();
httpClientBuilder.addInterceptorFirst( (HttpRequestInterceptor) interceptor );
httpClientBuilder.addInterceptorFirst( (HttpResponseInterceptor) interceptor );

// Use client with RestTemplate or on its own
HttpClient client = httpClientBuilder.build();

这是最小的双重拦截器:

public class ResponseTimeInterceptor implements HttpRequestInterceptor, HttpResponseInterceptor {
    private final Map<HttpContext, Long> requestMap = new MaxSizeHashMap<>( 50 );

    @Override
    public void process( HttpRequest httpRequest, HttpContext httpContext ) throws HttpException, IOException {
        requestMap.put( httpContext, System.currentTimeMillis() );
    }

    @Override
    public void process( HttpResponse httpResponse, HttpContext httpContext ) throws HttpException, IOException {
        long startTime = requestMap.getOrDefault( httpContext, 0L );
        long diff = System.currentTimeMillis() - startTime;
        System.out.println( "Response time: " + diff + "ms" );
    }
}

响应拦截器返回后,响应数据继续进入RestTemplate响应处理程序。

注意:MaxSizeHashMap取自https://stackoverflow.com/a/5601377

相关问题