并行化许多GET请求

use*_*079 4 java parallel-processing multithreading get httprequest

是否有任何有效的方法来并行化Java中的大量GET请求.我有一个200,000行的文件,每个行都需要来自Wikimedia的GET请求.然后我必须将一部分响应写入一个公共文件.我已将下面代码的主要部分粘贴为参考.

while ((line = br.readLine()) != null) {
    count++;
    if ((count % 1000) == 0) {
        System.out.println(count + " tags parsed");
        fbw.flush();
        bw.flush();
    }
    //System.out.println(line);
    String target = new String(line);
    if (target.startsWith("\"") && (target.endsWith("\""))) {
        target = target.replaceAll("\"", "");
    }
    String url = "http://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=xml&rvprop=timestamp&rvlimit=1&rvdir=newer&titles=";
    url = url + URLEncoder.encode(target, "UTF-8");
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");
    //add request header
    //con.setRequestProperty("User-Agent", USER_AGENT);
    int responsecode = con.getResponseCode();
    //System.out.println("Sending 'Get' request to URL: " + url);
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);         
    }
    Document doc = loadXMLFromString(response.toString());
    NodeList x = doc.getElementsByTagName("revisions");
    if (x.getLength() == 1) {
        String time = x.item(0).getFirstChild().getAttributes().item(0).getTextContent().substring(0,10).replaceAll("-", "");
        bw.write(line + "\t" + time + "\n");
    } else if (x.getLength() == 2) {
        String time = x.item(1).getFirstChild().getAttributes().item(0).getTextContent().substring(0, 10).replaceAll("-", "");          
        bw.write(line + "\t" + time + "\n");
    } else {
        fbw.write(line + "\t" + "NULL" + "\n");
    }
}
Run Code Online (Sandbox Code Playgroud)

我用Google搜索,似乎有两种选择.一种是创建线程,另一种是使用称为Executor的东西.有人可以提供一些指导,说明哪一个更适合这项任务?

Ste*_*n C 5

如果您确实需要通过GET请求来实现,我建议您使用带有线程池(2或3)的ThreadPoolExecutor,以避免重载维基百科服务器.这将避免大量编码......

还要考虑使用Apache HttpClient库(具有持久连接!).


但是使用数据库下载选项要好得多.根据您的操作,您可以选择较小的下载之一. 本页讨论了各种选项.

注意:维基百科更喜欢人们下载数据库转储(等等)而不是在他们的Web服务器上敲击.