- 初始化連接數:默認值 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.\n"); 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(); } }