我想测量 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/