- 初始化连接数:默认值 0
- 同一时刻可分配最大连接数:默认值 8 ,设置为负数时不做限制
- 最大空闲连接,默认值 8 ,超出连接将被释放
- 最小空闲连接数,默认值 0
- 请求连接最大等待时间(毫秒),默认值 无限期 ,超出时间将抛出异常
conn = dataSource.getConnection(); // 时间点T1
// T1 至 T2 这段时间,该连接为活跃连接
conn.close(); // 时间点T2
// 时间点T2 之后,连接被连接池回收,如果此时idle连接超过maxIdle ,则会释放连接
case:
package cn.zno.jdbc.dbcp; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; // // To compile this example, you'll want: // * commons-pool-2.3.jar // * commons-dbcp-2.1.jar // in your classpath. // // To run this example, you'll want: // * commons-pool-2.3.jar // * commons-dbcp-2.1.jar // * commons-logging-1.2.jar // in your classpath. // public class DbcpTool { @SuppressWarnings("unused") public static void main(String[] args) throws SQLException { DataSource dataSource = setupDataSource(); Connection conn1 = dataSource.getConnection(); printDataSourceStats(dataSource);// 活跃1 空闲0 |新建1个 conn1.close(); printDataSourceStats(dataSource);// 活跃0 空闲1 | Connection conn2 = dataSource.getConnection(); printDataSourceStats(dataSource);// 活跃1 空闲0 |使用之前的 Connection conn3 = dataSource.getConnection(); printDataSourceStats(dataSource);// 活跃2 空闲0 |新建第2个 conn2.close(); printDataSourceStats(dataSource);// 活跃1 空闲1 | conn3.close(); printDataSourceStats(dataSource);// 活跃0 空闲2 | } public static DataSource setupDataSource() { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName("oracle.jdbc.OracleDriver"); ds.setUrl("jdbc:oracle:thin:@//172.16.50.67:1521/orcl"); ds.setUsername("e_channel"); ds.setPassword("e_channel_test"); ds.setInitialSize(0); ds.setMaxTotal(3); ds.setMaxIdle(3); ds.setMinIdle(1); ds.setMaxWaitMillis(10000); System.out.println("MaxTotal: " + ds.getMaxTotal()); System.out.println("MaxIdle: " + ds.getMaxIdle()); System.out.println("MinIdle: " + ds.getMinIdle()); System.out.println("MaxWaitMillis: " + ds.getMaxWaitMillis()); System.out.println("set up done. "); return ds; } public static void printDataSourceStats(DataSource ds) { BasicDataSource bds = (BasicDataSource) ds; System.out.println("NumActive: " + bds.getNumActive()); System.out.println("NumIdle: " + bds.getNumIdle()); System.out.println(); } public static void shutdownDataSource(DataSource ds) throws SQLException { BasicDataSource bds = (BasicDataSource) ds; bds.close(); } }