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
       }
     }
    }
    
  • 相关阅读:
    [Erlang 0106] Erlang实现Apple Push Notifications消息推送
    一场推理的盛宴
    [Erlang 0105] Erlang Resources 小站 2013年1月~6月资讯合集
    [Erlang 0104] 当Erlang遇到Solr
    [Erlang 0103] Erlang Resources 资讯小站
    history.go(-1)和History.back()的区别
    [Java代码] Java用pinyin4j根据汉语获取各种格式和需求的拼音
    spring中context:property-placeholder/元素
    Java中的异常处理:何时抛出异常,何时捕获异常?
    用Jersey构建RESTful服务1--HelloWorld
  • 原文地址:https://www.cnblogs.com/ssgao/p/8829320.html
Copyright © 2011-2022 走看看