zoukankan      html  css  js  c++  java
  • 爬虫中的连接池

    在前面的内容中已经可以深刻的体会到,不管是post请求还是get请求,每次都要创建HttpClient,会出现频繁的创建和销毁问题。

    对于上面的问题我们可以使用连接池来解决

    具体代码:

    package cn.itcast.crawler.test;

    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.HttpClients;
    import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
    import org.apache.http.util.EntityUtils;

    import java.io.IOException;

    public class HttpClientPoolTest {
    public static void main(String[] args) {
    //创建连接池管理器
    PoolingHttpClientConnectionManager cm=new PoolingHttpClientConnectionManager();
    //设置最大连接数
    cm.setMaxTotal(100);
    //设置每个主机的最大连接数
    cm.setDefaultMaxPerRoute(10);
    //使用连接池管理器发起请求
    doGet(cm);
    doGet(cm);
    }

    private static void doGet(PoolingHttpClientConnectionManager cm) {
    //这样操作以后及不是每次都创建新的HttpClient,而是从连接池中获取
    CloseableHttpClient httpClient= HttpClients.custom() .setConnectionManager(cm).build();
    HttpGet httpGet=new HttpGet("http://www.itcast.cn");
    CloseableHttpResponse response=null;
    try {
    response=httpClient.execute(httpGet);
    if(response.getStatusLine().getStatusCode()==200){
    String content=EntityUtils.toString(response.getEntity(),"utf8");
    System.out.println(content.length());
    }

    } catch (IOException e) {
    e.printStackTrace();
    }finally {
    if(response!=null){
    try {
    response.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    //不能关闭httpClient,因为它由连接池进行管理了
    //httpClient.close();
    }

    }
    }
    }
    对于这个连接池是否有作用,可以通过打断点来查看
  • 相关阅读:
    SSL JudgeOnline 1194——最佳乘车
    SSL JudgeOnline 1457——翻币问题
    SSL JudgeOnlie 2324——细胞问题
    SSL JudgeOnline 1456——骑士旅行
    SSL JudgeOnline 1455——电子老鼠闯迷宫
    SSL JudgeOnline 2253——新型计算器
    SSL JudgeOnline 1198——求逆序对数
    SSL JudgeOnline 1099——USACO 1.4 母亲的牛奶
    SSL JudgeOnline 1668——小车载人问题
    SSL JudgeOnline 1089——USACO 1.2 方块转换
  • 原文地址:https://www.cnblogs.com/juddy/p/13118058.html
Copyright © 2011-2022 走看看