0

给出下面的代码,我怎样才能在线程结束时记录请求时间以获得一个最终的RequestTime?

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    new ClientRequestContextHolder();
    logger.info("request filter ("+ ClientRequestContextHolder.getContext().getAttribute("uniqueId") +") started");
    filterChain.doFilter(request, response);
    logger.info("request filter ("+ ClientRequestContextHolder.getContext().getAttribute("uniqueId") +") finished");
    long st = (long)ClientRequestContextHolder.getContext().getAttribute("request_start");
    logger.info("RequestTime: " + customFormat("###,###.###",(System.nanoTime() - st)) + "ns");

}

我当前的输出看起来像这样

INFO : com.app.context.ClientRequestContextHolder - initialized
INFO : com.app.filters.ClientRequestFilter - request filter (34) started
INFO : com.app.filters.ClientRequestFilter - request filter (34) started
INFO : com.app.filters.ClientRequestFilter - request filter (34) finished
INFO : com.app.filters.ClientRequestFilter - RequestTime: 7,958,694ns
INFO : com.app.filters.ClientRequestFilter - request filter (34) started
INFO : com.app.filters.ClientRequestFilter - request filter (34) started
INFO : com.app.filters.ClientRequestFilter - request filter (34) started
INFO : com.app.filters.ClientRequestFilter - request filter (34) finished
INFO : com.app.filters.ClientRequestFilter - RequestTime: 12,657,404ns
INFO : com.app.filters.ClientRequestFilter - request filter (34) started
INFO : com.app.filters.ClientRequestFilter - request filter (34) finished
INFO : com.app.filters.ClientRequestFilter - RequestTime: 13,942,554ns
INFO : com.app.filters.ClientRequestFilter - request filter (34) finished
INFO : com.app.filters.ClientRequestFilter - RequestTime: 14,579,297ns
INFO : com.app.filters.ClientRequestFilter - request filter (34) started
INFO : com.app.filters.ClientRequestFilter - request filter (34) finished
INFO : com.app.filters.ClientRequestFilter - RequestTime: 16,428,276ns
INFO : com.app.filters.ClientRequestFilter - request filter (34) started
INFO : com.app.filters.ClientRequestFilter - request filter (34) finished
INFO : com.app.filters.ClientRequestFilter - RequestTime: 17,329,786ns
INFO : com.app.filters.ClientRequestFilter - request filter (34) started
INFO : com.app.filters.ClientRequestFilter - request filter (34) finished
INFO : com.app.filters.ClientRequestFilter - RequestTime: 42,787,490ns
INFO : com.app.filters.ClientRequestFilter - request filter (34) finished
INFO : com.app.filters.ClientRequestFilter - RequestTime: 43,226,233ns
INFO : com.app.filters.ClientRequestFilter - request filter (34) finished
INFO : com.app.filters.ClientRequestFilter - RequestTime: 45,455,568ns
4

1 回答 1

0

知道了。

因为过滤器链是递归的,我只是在它上面添加了一个深度控制。最后,如果深度为 0,那么我计算打印结果。

于 2013-08-17T01:02:33.900 回答