如何在java中以有效的方式进行多个API调用
问题描述:
我有一个100k用户的列表。我必须遍历列表并对服务器进行API调用才能获得结果。每次我创建一个新的URL连接并进行APi调用,然后在读取输入流后关闭连接,但这需要花费太多时间。如何在java中以有效的方式进行多个API调用
是否有任何优化的方式来做到这一点,例如多次使用同一个URL连接实例而不是关闭它?或去另一个第三方库会提高执行速度?
我在我的循环中调用下面的方法来获取输出。
private String getOutput(String loginName) {
String responseStatus = null;
HttpURLConnection connection = null;
try {
URL url= new URL(<<https://api.junk.123.com/output>>);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("apikey", "authentication key");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
try(DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())){
JsonObject jsonParam = new JsonObject();
jsonParam.putString("loginName", "loginName");
outputStream.writeBytes(jsonParam.toString());
outputStream.flush();
}
//Get response
InputStream inputStream;
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
if(null == inputStream){
return String.valueOf(connection.getResponseCode());
}
StringBuilder response = new StringBuilder();
try (BufferedReader inputBuffer = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while (null != (line = inputBuffer.readLine())) {
response.append(line);
response.append("\r");
}
}
JsonObject jsonObject = new JsonObject(response.toString());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
responseStatus = "success";
} else {
responseStatus = String.valueOf(connection.getResponseCode()) + jsonObject.getString("errorMessage") ;
}
} catch (MalformedURLException e) {
logger.error("Malformed URL exception occurred while calling the API", entry.getKey(), e);
} catch (IOException e) {
logger.error("Creation of connection failed while calling the API", entry.getKey(), e);
} catch (Exception e) {
logger.error("Error occurred while calling the API", entry.getKey(), e);
} finally {
if (null != connection){
connection.disconnect();
}
}
return responseStatus;
}
答
这个问答&一个解释HTTP持久连接由HttpURLConnection的幕后实现:
然而,这可能是不够的。如果您使用单个客户端线程执行提取操作,则您将受限于往返时间的请求;即在第一个结果返回给你之前,你不能开始第二个请求。您可以通过使用多个客户端线程来解决这个问题。
然而(#2)并行发送多个请求也有其限制。超出某个特定点,您将使客户端,服务器或网络饱和。另外,一些服务器具有限制机制来限制客户端可以进行的请求数量。
获得最大吞吐量的方法是重新设计API,以便单个请求可以获取多个用户的信息。
您必须使用后台任务。 –
James Z感谢您的编辑。 – Jeeri