dbcp连接池配置
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${mysql.url}"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
<property name="defaultAutoCommit" value="false"/>
<property name="initialSize" value="2"/> <!-- 初始化连接数,默认值0 -->
<property name="minIdle" value="5"/> <!-- 最小空闲连接数,默认值0 -->
<property name="maxIdle" value="10"/> <!-- 最大空闲连接数,默认值8 -->
<property name="maxActive" value="20"/> <!-- 最大连接数,默认值8 -->
<property name="maxWait" value="1000"/> <!-- 最大获取连接池连接等待时间(毫秒) -->
<property name="removeAbandoned" value="true"/> <!-- 是否自动回收超时连接 -->
<property name="removeAbandonedTimeout" value="180"/> <!-- 超时时间(秒) -->
<property name="logAbandoned" value="true"/> <!-- 是否在自动回收超时连接的时候打印连接的超时错误 -->
<!-- 空闲时是否验证 -->
GenericObjectPool中针对pool管理,起了一个Evict的TimerTask定时线程进行控制
(可通过设置参数timeBetweenEvictionRunsMillis>0),定时对线程池中的链接进行validateObject校验,
对无效的链接进行关闭后,会调用ensureMinIdle,适当建立链接保证最小的minIdle连接数。
<property name="testWhileIdle" value="true"/>
<!-- 空闲对象回收器运行间隔(毫秒),若需要回收, 该值最好小于 minEvictableIdleTimeMillis值 -->
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="minEvictableIdleTimeMillis" value="3600000"/>
<!-- 被空闲对象回收器回收前在池中保持空闲状态的最小时间(毫秒) -->
</bean>
1.maxWait
The maximum number of milliseconds that the pool will wait (when there
are no available connections) for a connection to be returned before
throwing an exception, or <= 0 to wait indefinitely.
2.removeAbandoned
如果开启"removeAbandoned",那么连接在被认为泄露时可能被池回收.
这个机制在(getNumIdle() < 2) and (getNumActive() > getMaxActive() - 3)时被触发.
举例当maxActive=20, 活动连接为18,空闲连接为1时可以触发"removeAbandoned".
但是活动连接只有在没有被使用的时间超过"removeAbandonedTimeout"时才被删除,默认300秒.
一般会是几种情况出现需要removeAbandoned:
代码未在finally释放connection
遇到数据库死锁
3.validationQuery
/**
* The SQL query that will be used to validate connections from this pool
* before returning them to the caller. If specified, this query
* <strong>MUST</strong> be an SQL SELECT statement that returns at least
* one row.
*/
SQL查询,用来验证从连接池取出的连接,在将连接返回给调用者之前.
如果指定,则查询必须是一个SQL SELECT并且必须返回至少一行记录.
如可指定为:SELECT NOW() FROM DUAL
4.testOnBorrow
默认true
指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个.
注意: 设置为true后如果要生效,validationQuery参数必须设置为非空字符串
5.testOnReturn
默认false
指明是否在归还到池中前进行检验
注意: 设置为true后如果要生效,validationQuery参数必须设置为非空字符串