HttpClient多執行緒


多執行緒程式包含兩個或多個可以並行執行的部分,每個部分可以同時處理不同的任務,從而最佳地利用可用資源。

可以通過編寫多執行緒HttpClient程式來執行來自多個執行緒的請求。

如果要連續從執行緒執行多個用戶端請求,則需要建立ClientConnectionPoolManager。它維護一個HttpClientConnections池,並提供來自執行緒的多個請求。

連線管理器根據路由匯集連線。如果管理器具有特定路由的連線,則它通過從池中租用現有連線而不是建立新連線來在這些路由中提供新請求。

按照步驟執行多個執行緒的請求 -

第1步 - 建立用戶端連線池管理器
通過範例化PoolingHttpClientConnectionManager類來建立用戶端連線池管理器。

PoolingHttpClientConnectionManager connManager = new
   PoolingHttpClientConnectionManager();

第2步 - 設定最大連線數
使用setMaxTotal()方法設定池中的最大連線數。

//Set the maximum number of connections in the pool
connManager.setMaxTotal(100);

第3步 - 建立ClientBuilder物件
通過使用setConnectionManager()方法設定連線管理器來建立ClientBuilder物件,如下所示 -

HttpClientBuilder clientbuilder =
HttpClients.custom().setConnectionManager(connManager);

第4步 - 建立HttpGet請求物件

通過將所需的URI作為引數傳遞給其建構函式來範例化HttpGet類。

HttpGet httpget1 = new HttpGet("URI1");
HttpGet httpget2 = new HttpGet("URI2");
. . . . . . . . . . . .

第5步 - 實現run方法
確保已建立一個類,使其成為一個執行緒(通過擴充套件執行緒類或通過實現Runnable介面)並實現run方法。

public class ClientMultiThreaded extends Thread {
   public void run() {
      //Run method implementation . . . . . . . . . .
   }
}

第6步 - 建立Thread物件

通過範例化上面建立的Thread類(ClientMultiThreaded)來建立執行緒物件。

將HttpClient物件,相應的HttpGet物件和表示ID的整數傳遞給這些執行緒。

ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1);
ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2);
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

第7步 - 啟動並加入執行緒
使用start()方法啟動所有執行緒,並使用join()方法加入。

thread1.start();
thread2.start();
. . . . . . . .
thread1.join();
thread2.join();
. . . . . . . . . . . .

第8步 - 執行方法實現

在run方法中,執行請求,檢索響應並列印結果。

範例

以下範例演示了從多個執行緒同時執行HTTP請求。在此範例中,嘗試執行來自各種執行緒的各種請求,並嘗試列印狀態以及每個用戶端讀取的位元組數。

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

public class ClientMultiThreaded extends Thread {
   CloseableHttpClient httpClient;
   HttpGet httpget;
   int id;

   public ClientMultiThreaded(CloseableHttpClient httpClient, HttpGet httpget,
   int id) {
      this.httpClient = httpClient;
      this.httpget = httpget;
      this.id = id;
   }
   @Override
   public void run() {
      try{
         //Executing the request
         CloseableHttpResponse httpresponse = httpClient.execute(httpget);

         //Displaying the status of the request.
         System.out.println("status of thread "+id+":"+httpresponse.getStatusLine());

         //Retrieving the HttpEntity and displaying the no.of bytes read
         HttpEntity entity = httpresponse.getEntity();
         if (entity != null) {
            System.out.println("Bytes read by thread thread "+id+":
               "+EntityUtils.toByteArray(entity).length);
         }
      }catch(Exception e){
         System.out.println(e.getMessage());
      }
   }

   public static void main(String[] args) throws Exception {

      //Creating the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class.
      PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();

      //Set the maximum number of connections in the pool
      connManager.setMaxTotal(100);

      //Create a ClientBuilder Object by setting the connection manager
      HttpClientBuilder clientbuilder = HttpClients.custom().setConnectionManager(connManager);

      //Build the CloseableHttpClient object using the build() method.
      CloseableHttpClient httpclient = clientbuilder.build();

      //Creating the HttpGet requests
      HttpGet httpget1 = new HttpGet("https://www.tw511.com/");
      HttpGet httpget2 = new HttpGet("http://www.kaops.com/");
      HttpGet httpget3 = new HttpGet("https://www.qries.com/");
      HttpGet httpget4 = new HttpGet("https://in.yahoo.com/");

      //Creating the Thread objects
      ClientMultiThreaded thread1 = new ClientMultiThreaded(httpclient,httpget1, 1);
      ClientMultiThreaded thread2 = new ClientMultiThreaded(httpclient,httpget2, 2);
      ClientMultiThreaded thread3 = new ClientMultiThreaded(httpclient,httpget3, 3);
      ClientMultiThreaded thread4 = new ClientMultiThreaded(httpclient,httpget4, 4);

      //Starting all the threads
      thread1.start();
      thread2.start();
      thread3.start();
      thread4.start();

      //Joining all the threads
      thread1.join();
      thread2.join();
      thread3.join();
      thread4.join();
   }
}

執行上面範例程式碼,得到以下結果:

status of thread 1: HTTP/1.1 200 OK
Bytes read by thread thread 1: 36907
status of thread 2: HTTP/1.1 200 OK
Bytes read by thread thread 2: 13725
status of thread 3: HTTP/1.1 200 OK
Bytes read by thread thread 3: 17319
status of thread 4: HTTP/1.1 200 OK
Bytes read by thread thread 4: 127018