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的东西.有人可以提供一些指导,说明哪一个更适合这项任务?
| 归档时间: |
|
| 查看次数: |
237 次 |
| 最近记录: |