zoukankan      html  css  js  c++  java
  • httpclient 多线程请求

    线程请求执行

    当配备一个线程池管理器后,如PollingClientConnectionManager,HttpClient就能使用执行着的多线程去执行并行的多请求。

    PollingClientConnectionManager会基于它的配置去分配连接。如果一个指定的路由连接已经被租用了,连接请求会被阻塞直到有一个连接被释回到池里。
    可以给http.connmanager.timeout设定一个正值以确保连接管理器在连接请求操作里不会无限的阻塞下去。如果连接请求不能在指定的时间获取服务就抛出
    ConnectionPoolTimeoutException异常。
    PollingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    CloseableHttpClient httpClient = HttpClients
                                     .custom()
                                     .setConnectionManager(cm)
                                     .build();
    //URIs to perform GETs on
    String[] urisToGet={
     "http://www.domain1.com/",
     "http://www.domain2.com/",
     "http://www.domain3.com/",
     "http://www.domain4.com/"
    };
    //create a thread for each URI
    GetThread[] threads = new GetThread[uriToGet.length];
    for(int i=0;i<thread.length;i++){
      HttpGet httpget = new HttpGet(urisToGet[i]);
      threads[i]=new GetThread(httpClient,httpget);
    }
    //start the threads
    for(int j=0;j<threads.length;j++){
      threads[j].start();
    }
    //join the threads
    for(int j=0;j<threads.length;j++){
      threads[j].join();
    }
    

    HttpClient实例是线程安全的并且可以在执行着的多线程之间共享,并强烈推荐每个线程维护自己的HttpContext专用实例。

    Static class GetThread extends Thread{
     private final CloseableHttpClient httpClient;
     private final HttpContext context;
     private final HttpGet httpget;
    ​
     public GetThread(CloseableHttpClient httpClient, HttpGet httpGet){
       this.httpClient = httpClient;
       this.context=HttpClientContext.create();
       this.httpget=httpget;
     }
    ​
     public void run(){
      try{
         CloseableHttpResponse response = httpClient.execute(httpGet,context);
         try{
           HttpEntity entity = response.getEntity();
          }finally{
            response.close();
          }
       }catch(ClientProtocolException ex){
        //handle protocol errors
       }catch(IOException ex){
         //Handle I/O errors
       }
     }
    }
    
  • 相关阅读:
    【Jmeter】分布式并发测试
    【博客迁移】
    设置超出范围有滚动条
    table中td,th不能设置margin
    文字和input对不齐怎么办
    改变radio单选按钮的样式
    transition的用法以及animation的用法
    选择后代元素或点击元素的方法
    如何简单实用hammer
    添加aimate动画
  • 原文地址:https://www.cnblogs.com/ssgao/p/8829320.html
Copyright © 2011-2022 走看看