Apache HttpClient: varios subprocesos

Un programa de subprocesos múltiples contiene dos o más partes que pueden ejecutarse simultáneamente y cada parte puede manejar una tarea diferente al mismo tiempo haciendo un uso óptimo de los recursos disponibles.

Puede ejecutar solicitudes de varios subprocesos escribiendo un programa HttpClient multiproceso.

Si desea ejecutar varias solicitudes de clientes desde subprocesos de forma consecutiva, debe crear un ClientConnectionPoolManager. Mantiene una piscina deHttpClientConnections y atiende múltiples solicitudes de subprocesos.

El administrador de conexiones agrupa las conexiones según la ruta. Si el administrador tiene conexiones para una ruta en particular, entonces atiende nuevas solicitudes en esas rutas alquilando una conexión existente del grupo, en lugar de crear una nueva.

Siga los pasos para ejecutar solicitudes de varios subprocesos:

Paso 1: creación del administrador del grupo de conexiones del cliente

Cree el administrador del grupo de conexiones del cliente creando una instancia del PoolingHttpClientConnectionManager clase.

PoolingHttpClientConnectionManager connManager = new
   PoolingHttpClientConnectionManager();

Paso 2: establece el número máximo de conexiones

Establezca el número máximo de conexiones en el grupo mediante el setMaxTotal() método.

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

Paso 3: crear un objeto ClientBuilder

Crear un ClientBuilder Objeto configurando el administrador de conexiones usando el setConnectionManager() método como se muestra a continuación -

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

Paso 4: crear los objetos de solicitud HttpGet

Cree una instancia de la clase HttpGet pasando el URI deseado a su constructor como parámetro.

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

Paso 5: implementación del método de ejecución

Asegúrese de haber creado una clase, convertirla en un hilo (ya sea extendiendo la clase del hilo o implementando la interfaz Runnable) e implementado el método de ejecución.

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

Paso 6: crear objetos Thread

Cree objetos de hilo creando una instancia de la clase Thread (ClientMultiThreaded) creada anteriormente.

Pase un objeto HttpClient, el objeto HttpGet respectivo y un entero que represente el ID a estos subprocesos.

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

Paso 7: inicia y une los hilos

Inicie todos los hilos usando start() método y únete a ellos usando la combinación method().

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

Paso 8: ejecutar la implementación del método

Dentro del método de ejecución, ejecute la solicitud, recupere la respuesta e imprima los resultados.

Ejemplo

El siguiente ejemplo demuestra la ejecución de solicitudes HTTP simultáneamente desde múltiples subprocesos. En este ejemplo, intentamos ejecutar varias solicitudes de varios subprocesos e intentamos imprimir el estado y la cantidad de bytes leídos por cada cliente.

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.tutorialspoint.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();
   }
}

Salida

Al ejecutarse, el programa anterior genera la siguiente salida:

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