java - 测量 Spring RestTemplate HTTP 请求时间

标签 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 请求的时间?

最佳答案

您可以使用 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>

关于java - 测量 Spring RestTemplate HTTP 请求时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13286743/

相关文章:

java代理和Web服务身份验证

java - 错误: constructor Thread in class Thread cannot be applied to given types;

java.lang.IllegalArgumentException : Cannot bind argument at index 0 because the index is out of range. 该语句有4个参数

c++ - 如何跨内核同步 TSC?

performance - 调用 __device__ 函数会影响 CUDA 中使用的寄存器数量吗?

Java Web 服务客户端调用 Web 方法时出现 NullPointerException

java - 如何以编程方式隐藏 android 一些但不是全部的 XML 输出中的查看项目?

java - 当文本包含换行符时,JTextPane 中的显着性能差异

iphone - 是否有 NSURLConnection 的可靠替代方案?

database - odsi和odi的区别