【问题标题】:Using Jsoup connect() in a loop. The first request is always much slower than all other subsequent ones在循环中使用 Jsoup connect()。第一个请求总是比所有其他后续请求慢得多
【发布时间】:2020-03-11 02:35:26
【问题描述】:

我正在创建一个小应用程序来测量加载 HTML 文档需要多长时间,每隔 x 秒检查一次。

我在循环中使用 jsoup:

    Connection.Response response = null;

    for (int i = 0; i < totalGets; i++) {
        long startTime = System.currentTimeMillis();

        try {
            response = Jsoup.connect(url)
                    .userAgent(USER_AGENT)  //just using a Firefox user-agent
                    .timeout(30_000)
                    .execute();
        } catch (IOException e) {
            if (e.getMessage().contains("connect timed out")) {
                System.out.println("Request timed out after 30 seconds!");
            }
        }

        long currentTime = System.currentTimeMillis();

        System.out.println("Response time: " + (currentTime - startTime) + "ms" + "\tResponse code: " + response.statusCode());

        sleep(2000);
    }

我遇到的问题是,无论是哪个网站,jsoup 连接的第一次执行总是比所有后续执行都慢。

这是我在 https://www.google.com 上的输出

Response time: 934ms    Response code: 200
Response time: 149ms    Response code: 200
Response time: 122ms    Response code: 200
Response time: 136ms    Response code: 200
Response time: 128ms    Response code: 200

这是我在http://stackoverflow.com得到的信息

Response time: 440ms    Response code: 200
Response time: 182ms    Response code: 200
Response time: 187ms    Response code: 200
Response time: 193ms    Response code: 200
Response time: 185ms    Response code: 200

为什么第一次连接后总是更快?有没有更好的方法来确定文档的加载速度?

【问题讨论】:

标签: java jsoup document


【解决方案1】:

1. Jsoup 必须先运行一些样板代码,然后才能触发第一个请求。我不会将第一个请求计入您的测量中,因为所有初始化都会影响第一个请求的时间。

2. 如 cmets 中所述,许多网站会将响应缓存几秒钟。根据您要测量的网站,您可以使用一些技巧让网络服务器每次都生成一个新网站。这样的技巧可能是添加时间戳参数。通常_ 用于此目的(如http://url/path/?pameter1=val1&_=ts)。或者,您可以在 HTTP 请求中不发送缓存标头。然而,这些技巧都不能强迫网络服务器按照你想要的方式运行。因此,您可以在每个请求之间等待超过 30 秒。

【讨论】:

  • 我最终让它忽略了第一个请求,并添加了一些标头以防止缓存。谢谢!
【解决方案2】:

我认为除了@luksch 点之外还有另一个因素,我认为Java 保持连接活动几秒钟,也许可以节省协议旅行的时间。

如果您使用.header("Connection", "close"),您会看到更一致的时间。

您可以使用嗅探器检查连接是否保持活动状态。至少我可以看到重复使用的端口号(当然是源端口)。

编辑:

可能会增加第一次请求时间的另一件事是 DNS 查找 ...

【讨论】:

  • 是的。我忘记提及的所有事情。 +1
【解决方案3】:

另一个潜在原因是 JVM 在后台进行 JIT 优化,将 java 字节码转换为本地指令以提高速度。

第一次运行代码时速度很慢,因为代码尚未优化。由于优化已经完成,接下来的几轮会更快。

解析 html 页面是一项计算量很大的工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2012-03-15
    • 2012-10-05
    • 2020-05-31
    • 1970-01-01
    • 2018-10-27
    • 2016-05-13
    相关资源
    最近更新 更多