我需要循环多次调用 api 端点。虽然连接路径保持不变,但每次调用时都会有一个参数发生变化。我已经像下面这样写了。 由于该参数,我在每次迭代开始时打开连接,并在最后关闭它。这是每次打开和关闭套接字。我想知道是否有更好的方法来做到这一点?另外,如果我想测量连接开销,我该怎么做? 我正在使用 HttpURLConnection,但我可以选择任何其他库,如果这能更好地满足我的目的。
try {
String dataUrl = serviceBaseURL + "some_path";
BigDecimal count = new BigDecimal(0);
BigDecimal offset = new BigDecimal(0);
BigDecimal limit = new BigDecimal(20);
do {
// getting the params required for this connection. only the offset param changes in each call.
String query = getQuery(offset, limit);
URL url = new URL(dataUrl + query);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String encodedURL = uri.toASCIIString();
URL connUrl = new URL(encodedURL);
HttpURLConnection conn = (HttpURLConnection)connUrl.openConnection();
conn.setRequestMethod("GET");
int status = conn.getResponseCode();
if (status != 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
throw new Exception("Error: "+content.toString());
} else {
// processing response
....
....
count = (BigDecimal)contentJson.get("count");
}
conn.disconnect();
offset = offset.add(limit);
} while (count.compareTo(offset) >= 0);
} catch (Exception exception) {
System.out.println(exception.getMessage());
exception.printStackTrace();
}
您可以使用 CompletableFuture 来满足您的要求。
for (int i = 0; i < noOfLoop; i++) {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> yourMethod());
}
现在,您可以根据需要修改代码。您也可以使用 SupplyAsync 方法。请参阅 - runAsync 与 SupplyAsync
并行流也是一个不错的选择。
IntStream.range(0, noOfLoop).parallel().forEach(i -> yourMethod());
您也可以使用简单的线程创建机制。