1

在我的阀门中,我得到了我的 http 查询的执行时间:

public void invoke(Request request, Response response) 
throws IOException, ServletException {
long t1 = System.currentTimeMillis();
getNext().invoke(request, response);
long t2 = System.currentTimeMillis();
long time = t2 - t1;
...
}

我怀疑我这样得到的时间,不仅给了我服务器端的执行时间,还给了我网络时间?是否可以 ?

(因为根据发出请求的客户端,测量的平均时间与一个 IP 不同,我有 70 毫秒的平均时间和另一个 270 毫秒的 IP)

我在过滤器中编写了完全相同的代码:

long before = System.currentTimeMillis();
chain.doFilter(request, response);
long after = System.currentTimeMillis();

,但在我的测试中,阀门和过滤器中的执行时间是相同的......

我对只获取我的 servlet 的执行时间更感兴趣。但如果我也能得到发送最后一个字节的时间,我会感兴趣的。

非常感谢您向我澄清有关阀门和过滤器的知识。

4

1 回答 1

3

我怀疑我这样得到的时间,不仅给了我服务器端的执行时间,还给了我网络时间?是否可以 ?

这是正确的。这样,总时间中至少包含了一部分涉及传输请求体的网络时间。一旦请求被完全读取和解析,valve/filter/servlet 代码就会被直接调用。此时请求正文不一定完全读取。请求正文包含客户端作为请求的一部分通过网络发送的任何内容(例如提交的表单数据)。只有当过滤器/servlet 开始读取并解析完整的请求体时,例如getParameter()getReader()getInputStream()等,才会真正传输请求体的所有字节。

您可能希望以仅在完全读取请求正文后才开始的方式重写执行时间测量。这意味着您确实必须在 servlet 内部对其进行测量。

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Read the request body.
    String foo = request.getParameter("foo");
    String bar = request.getParameter("bar");
    // ...

    // Now, start the stopwatch.
    long startTime = System.nanoTime();

    // Now, do the business job.
    someService.process(foo, bar, ...);
    // ...

    // Now, stop the stopwatch.
    long elapsedTime = System.nanoTime() - startTime;

    // I don't think that you want to include JSP rendering in total time, right?
    request.getRequestDispatcher("/WEB-INF/some.jsp").forward(request, response);
}

(请注意,我使用它,System#nanoTime()因为它具有更好的准确性)

于 2011-09-12T16:25:30.677 回答