我是靠谱客的博主 健壮小松鼠,最近开发中收集的这篇文章主要介绍HttpComponents 之客户端连接池1.配置参数2.拿到httpClient3.示例代码4.回收过期链接5.注意,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1.配置参数

org.apache.http.impl.conn.PoolingHttpClientConnectionManager

类。用于管理httpClient连接池。调用默认构造函数即可得到。

org.apache.http.impl.conn.PoolingHttpClientConnectionManager.setMaxTotal(int max)

设置最大的连接数,即tcp连接数。

 void org.apache.http.impl.conn.PoolingHttpClientConnectionManager.setDefaultMaxPerRoute(int max)

设置每个路由的默认最大连接数。默认为2。也就是说你连qq.com:80的tcp个数最多为2。

void org.apache.http.impl.conn.PoolingHttpClientConnectionManager.setMaxPerRoute(HttpRoute route, int max)

设置指定路由的最大连接数。

2.拿到httpClient

HttpClientBuilder org.apache.http.impl.client.HttpClients.custom()

拿到HttpClientBuilder 。

HttpClientBuilder org.apache.http.impl.client.HttpClientBuilder.setConnectionManager(HttpClientConnectionManager connManager)

将PoolingHttpClientConnectionManager对象传进去。注意返回类型,可链式调用。

HttpClientBuilder org.apache.http.impl.client.HttpClientBuilder.setDefaultRequestConfig(RequestConfig config)

将RequestConfig对象传进去。

CloseableHttpClient org.apache.http.impl.client.HttpClientBuilder.build()

至此拿到了httpClient对象。它是线程安全的。

3.示例代码

也可见yichuutil项目。
package com.yichudu.yichuutil;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.routing.HttpRoute;
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;

public class PoolingHttpClient {
	//thread-safe
	private static CloseableHttpClient httpClient;
	private static PoolingHttpClientConnectionManager cm;
	static {
		init();
		closeExpiredConnectionsPeriodTask(60);
	}
	static void init(){
		cm = new PoolingHttpClientConnectionManager();
		// max connections
		cm.setMaxTotal(20);
		// max connections per route
		cm.setDefaultMaxPerRoute(2);
		// set max connections for a specified route
		cm.setMaxPerRoute(new HttpRoute(new HttpHost("locahost", 80)), 50);

		final RequestConfig requestConfig = RequestConfig.custom()
				// the socket timeout (SO_TIMEOUT) in milliseconds
				.setSocketTimeout(5000)
				// the timeout in milliseconds until a connection is established. 
				.setConnectTimeout(5000)
				// the timeout in milliseconds used when requesting a connection from the connection pool.
				.setConnectionRequestTimeout(5000)
				.build();
		httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build();
	}

	public static String get(String url) throws ClientProtocolException, IOException {
		CloseableHttpResponse response1 = null;
		Scanner scanner=null;
		try {
			HttpGet httpGet = new HttpGet(url);
			//sync
			response1 = httpClient.execute(httpGet);
			System.out.println(response1.getStatusLine());
			HttpEntity entity1 = response1.getEntity();
			InputStream instream = entity1.getContent();
			StringBuilder sb = new StringBuilder();
			scanner=new Scanner(instream, "utf-8");
			while (scanner.hasNextLine()) 
				sb.append(scanner.nextLine() + "n");
			EntityUtils.consume(entity1);
			return sb.toString();
		} finally {
			if(scanner!=null)
				scanner.close();
			if(response1!=null)
				response1.close();
		}
	}
	private static void closeExpiredConnectionsPeriodTask(int timeUnitBySecond){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(!Thread.currentThread().isInterrupted()){
					try {
						TimeUnit.SECONDS.sleep(timeUnitBySecond);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					cm.closeExpiredConnections();
				}
				
			}
		}).start();
	}

	public static void main(String[] args) throws ClientProtocolException, IOException {
		//get();
	}
}

4.回收过期链接

服务端若资源紧张,可能关闭一些我们已经建立好的链接。而连接池自己不会关,所以需要一个定时任务来清理。PoolingHttpClientConnectionManager类已经提供了此方法。
void org.apache.http.impl.conn.PoolingHttpClientConnectionManager. closeExpiredConnections()


图4-1 官网相关介绍,清理过期链接

5.注意

调用CloseableHttpResponse org.apache.http.impl.client.CloseableHttpClient. execute(HttpUriRequest request)时,会从连接池中找出一条链接通路来通信,此方法仍是同步的。所以要想做到并发通信,数据库连接池必须配合多线程使用。

最后

以上就是健壮小松鼠为你收集整理的HttpComponents 之客户端连接池1.配置参数2.拿到httpClient3.示例代码4.回收过期链接5.注意的全部内容,希望文章能够帮你解决HttpComponents 之客户端连接池1.配置参数2.拿到httpClient3.示例代码4.回收过期链接5.注意所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(76)

评论列表共有 0 条评论

立即
投稿
返回
顶部