我想知道能否使用过滤器(例如CorsFilter)来测量时间并将所花费的时间放到消息本身上。我知道以下代码是可行的:
头信息仅包括开始时间,而不包括结束时间。我认为这是因为消息已经发送,所以修改对象将没有任何效果。
更新
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
long startTime = System.nanoTime();
chain.doFilter(request, response);
long endTime = System.nanoTime();
System.out.println("Time: " + (endTime - startTime) );
}
当然,这会输出总时间(以秒为单位)。我想把时间放到返回响应的头部,以便接收者可以查看头部并了解处理所需的时间。以下代码无法工作:
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
long startTime = System.nanoTime();
if(response instanceof HttpServletResponse) {
HttpServletResponse httpResp = (HttpServletResponse)response;
httpResp.addHeader("Start-time", Long.toString(startTime));
}
chain.doFilter(request, response);
long endTime = System.nanoTime();
if(response instanceof HttpServletResponse) {
HttpServletResponse httpResp = (HttpServletResponse)response;
httpResp.addHeader("End-time", Long.toString(endTime));
}
}
有没有通过使用过滤器将计时放入头信息的优雅/聪明解决方案?
谢谢,
菲尔
我已经研究了使用HttpServletResponseWrapper来解决此问题。这仍然无法在响应标头中输出XXX-EndTime或YYY-EndTime。
@Override
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
long startTime = System.nanoTime();
if(response instanceof HttpServletResponse) {
HttpServletResponse httpResp = (HttpServletResponse)response;
httpResp.addHeader("Access-Control-Allow-Origin", "*");
httpResp.addHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
httpResp.addHeader("Allow", "GET, HEAD, OPTIONS");
httpResp.addHeader("Access-Control-Allow-Headers", "*");
httpResp.addHeader("A-Runtime", Long.toString(startTime));
}
OutputStream out = response.getOutputStream();
GenericResponseWrapper wrapper = new GenericResponseWrapper((HttpServletResponse) response);
chain.doFilter(request,wrapper);
out.write(wrapper.getData());
if(response instanceof HttpServletResponse) {
HttpServletResponse httpResp = (HttpServletResponse)response;
httpResp.addHeader("XXX-EndTime", Long.toString(System.nanoTime() - startTime));
wrapper.addHeader("YYY-EndTime", Long.toString(System.nanoTime() - startTime));
}
out.close();
}