Apache-httpclient-multiple-threads

提供:Dev Guides
移動先:案内検索

Apache HttpClient-複数のスレッド

マルチスレッドプログラムには、同時に実行できる2つ以上の部分が含まれており、各部分は同時に使用可能なリソースを最適に使用して異なるタスクを処理できます。

マルチスレッド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クラス(ClientMultiThreaded)をインスタンス化して、スレッドオブジェクトを作成します。

HttpClientオブジェクト、それぞれのHttpGetオブジェクト、およびIDを表す整数をこれらのスレッドに渡します。

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

ステップ7-スレッドを開始して参加する

  • start()*メソッドを使用してすべてのスレッドを開始し、join * method()*を使用してそれらを結合します。
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("http://www.finddevguides.com/");
      HttpGet httpget2 = new HttpGet("http://www.google.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