java线程httpclient_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

HttpGet httpget = new HttpGet(urisToGet[i]);

threads[i]=new GetThread(httpClient,httpget);

}

//start the threads

for(int j=0;j

threads[j].start();

}

//join the threads

for(int j=0;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

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值