Apache HttpClient - Multiple Threads

Um programa multi-threaded contém duas ou mais partes que podem ser executadas simultaneamente e cada parte pode lidar com uma tarefa diferente ao mesmo tempo, fazendo uso otimizado dos recursos disponíveis.

Você pode executar solicitações de vários threads escrevendo um programa HttpClient multithread.

Se você deseja executar várias solicitações de cliente de threads consecutivamente, você precisa criar um ClientConnectionPoolManager. Ele mantém um pool deHttpClientConnections e atende a várias solicitações de threads.

O gerenciador de conexões agrupa as conexões com base na rota. Se o gerente tiver conexões para uma rota específica, ele atenderá a novas solicitações nessas rotas alugando uma conexão existente do pool, em vez de criar uma nova.

Siga as etapas para executar solicitações de vários threads -

Etapa 1 - Criação do gerenciador de pool de conexão do cliente

Crie o Client Connection Pool Manager instanciando o PoolingHttpClientConnectionManager classe.

PoolingHttpClientConnectionManager connManager = new
   PoolingHttpClientConnectionManager();

Etapa 2 - Definir o número máximo de conexões

Defina o número máximo de conexões no pool usando o setMaxTotal() método.

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

Etapa 3 - Criar um objeto ClientBuilder

Criar uma ClientBuilder Objeto configurando o gerenciador de conexões usando o setConnectionManager() método como mostrado abaixo -

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

Etapa 4 - Criar os objetos de solicitação HttpGet

Instancie a classe HttpGet passando o URI desejado para seu construtor como um parâmetro.

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

Etapa 5 - Implementando o método de execução

Certifique-se de ter criado uma classe, feito um thread (estendendo a classe de thread ou implementando a interface Runnable) e implementado o método run.

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

Etapa 6 - Criar objetos Thread

Crie objetos de thread instanciando a classe Thread (ClientMultiThreaded) criada acima.

Passe um objeto HttpClient, respectivo objeto HttpGet e, um inteiro representando o ID para esses threads.

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

Passo 7 - Comece e junte os tópicos

Comece todos os tópicos usando start() método e junte-os usando o método join method().

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

Etapa 8 - Executar implementação do método

Dentro do método run, execute a solicitação, recupere a resposta e imprima os resultados.

Exemplo

O exemplo a seguir demonstra a execução de solicitações HTTP simultaneamente de vários threads. Neste exemplo, estamos tentando executar várias solicitações de vários threads e tentando imprimir o status e o número de bytes lidos 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();
   }
}

Resultado

Ao ser executado, o programa acima gera a seguinte saída -

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