httpclient.properties 配置文件
#设置连接总数 200
httpclient.maxTotal=200
#设置单个地址的最大并发数
httpclient.defaultMaxPerRoute=20
#连接超时时间 10s
httpclient.connectTimeout=10000
#从连接池中获取到连接的最长时间 5s
httpclient.connectionRequestTimeout=5000
#数据传输的最长时间 2s
httpclient.socketTimeout=2*1000
#提交请求前测试连接是否可用
httpclient.staleConnectionCheckEnabled=true
applicationContext-httpclient.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 定义连接管理器 -->
<bean id="connectManage"
class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
<property name="maxTotal" value="${httpclient.maxTotal}"></property>
<property name="defaultMaxPerRoute" value="${httpclient.defaultMaxPerRoute}"></property>
</bean>
<!-- 定义 HttpClient工厂,这里使用HttpClientBuilder构建-->
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
<property name="connectionManager" ref="connectManage"></property>
</bean>
<!-- 定义httpclient对象,需要配置多例 -->
<bean class="org.apache.http.impl.client.CloseableHttpClient"
factory-bean="httpClientBuilder" factory-method="build" scope="prototype"></bean>
<!-- 定义requestConfig的工厂 -->
<bean id="requestConfig" class="org.apache.http.client.config.RequestConfig.Builder">
<property name="connectTimeout" value="${httpclient.connectTimeout}"></property>
<property name="connectionRequestTimeout" value="${httpclient.connectionRequestTimeout}"></property>
<property name="socketTimeout" value="${httpclient.socketTimeout}"></property>
<property name="staleConnectionCheckEnabled" value="${httpclient.staleConnectionCheckEnabled}"></property>
</bean>
<!-- 定义连接配置信息 -->
<bean class="org.apache.http.client.config.RequestConfig"
factory-bean="requestConfig" factory-method="build"></bean>
<!-- 定期清理无效的连接 -->
<bean class="com.allpay.demo.common.httpclient.IdleConnectionEvictor">
<constructor-arg index="0" ref="connectManage"></constructor-arg>
<!-- 间隔5分钟清理一次 -->
<constructor-arg index="1" value="5000" />
</bean>
</beans>
网友评论