2017-10-14 44 views
1

我有一個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; 
} 
+0

您必須使用後臺任務。 –

+0

James Z感謝您的編輯。 – Jeeri

回答

1

這個問答&一個解釋HTTP持久連接由HttpURLConnection的幕後實現:

然而,這可能是不夠的。如果您使用單個客戶端線程執行提取操作,則您將受限於往返時間的請求;即在第一個結果返回給你之前,你不能開始第二個請求。您可以通過使用多個客戶端線程來解決這個問題。

然而(#2)並行發送多個請求也有其限制。超出某個特定點,您將使客戶端,服務器或網絡飽和。另外,一些服務器具有限制機制來限制客戶端可以進行的請求數量。

獲得最大吞吐量的方法是重新設計API,以便單個請求可以獲取多個用戶的信息。

相關問題