【发布时间】:2017-05-04 18:44:45
【问题描述】:
我有一个程序需要从网页下载小文本文件,为此我编写了以下代码:
URLConnection connection = null; // Connection to the URL data
InputStreamReader iSR = null; // Stream of the URL data
BufferedReader bR = null; // Reader of URL data
URL url = null; // URL based on the specified link
// Open the connection to the URL web page
url = new URL(urlLink);
connection = url.openConnection();
// Initialize the Readers
iSR = new InputStreamReader(connection.getInputStream());
bR = new BufferedReader(iSR);
// Fetch all of the lines from the buffered reader and join them all
// together into a single string.
return bR.lines().collect(Collectors.joining("\n"));
不幸的是,我从中下载数据的服务器的 TTFB 等待时间很长。根据开发者工具 (F12),大约 90% 的总下载时间是 TTFB。如果我要下载大量文件,这会使我的 Java 程序下载速度非常慢。基本上,对于每个文件,我们打开一个连接,等待 250 毫秒,下载,打开一个连接,再等待 250 毫秒,下载,这对于大量文件来说非常慢。我能够使用线程来减少问题,因此我有大约 10 个线程,每个线程下载我需要的所有文件的一部分。这加快了我的程序,但它并没有解决我遇到的根本问题。每个线程仍然需要打开一个连接,等待 250 毫秒,下载,然后重复。我理想的解决方案是以某种方式同时发送所有请求并等待 250 毫秒让 TTFB 时间完成,然后从网页中单独下载所有数据。我能想到的唯一方法是创建 1000 个线程并在每个线程上打开一个 URL 连接,但这似乎是一种非常糟糕的方法。有没有其他方法可以打开多个 URL 连接并让 TTFB 期间同时发生?
【问题讨论】:
标签: java multithreading download