資料庫連線池是企業級 Java 應用程式的核心基礎設施,能有效管理連線資源、提升效能與穩定性。Apache Commons DBCP2 是成熟且廣泛使用的連線池實作。本文以 MyEclipse 2014 為開發環境,示範如何在 Web 專案中整合 DBCP2,包含專案結構、工具類、設定檔、連線池參數調校與實戰 DAO 範例。
testjdbc,含 web.xmlcom.szkingdom.dbcommons-dbcp2.jar、commons-pool2.jar、MySQL 驅動 mysql-connector-java.jar提供 castString、castInt、castLong、castDouble、castBoolean 等靜態方法,支援預設值與異常安全轉換,避免 NullPointerException 與 NumberFormatException。
isEmpty()、isNotEmpty() 封裝 trim() 與空字串檢查,簡化業務邏輯。
透過 Thread.currentThread().getContextClassLoader().getResourceAsStream() 讀取 classpath 下屬性檔,回傳 Properties 物件,並提供 getString、getInt、getBoolean 多載方法支援預設值。
# dbconfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/your_db
jdbc.username=your_user
jdbc.password=your_pass
static {
CONNECTION_HOLDER = new ThreadLocal<Connection>();
Properties conf = PropsUtil.loadProps("dbconfig.properties");
// 讀取驅動、URL、帳密
DATA_SOURCE = new BasicDataSource();
DATA_SOURCE.setDriverClassName(driver);
DATA_SOURCE.setUrl(url);
DATA_SOURCE.setUsername(username);
DATA_SOURCE.setPassword(password);
// 關鍵參數調校
DATA_SOURCE.setMaxTotal(60); // 最大活躍連線
DATA_SOURCE.setInitialSize(10); // 初始連線數
DATA_SOURCE.setMinIdle(8); // 最小閒置連線
DATA_SOURCE.setMaxIdle(16); // 最大閒置連線
DATA_SOURCE.setMaxWaitMillis(20000); // 取得連線最長等待 20 秒
DATA_SOURCE.setTestOnBorrow(true); // 借用前驗證
DATA_SOURCE.setRemoveAbandonedTimeout(180); // 棄用連線回收逾時 180 秒
DATA_SOURCE.setRemoveAbandonedOnBorrow(true);
DATA_SOURCE.setTestOnReturn(true);
DATA_SOURCE.setRemoveAbandonedOnMaintenance(true);
DATA_SOURCE.setLogAbandoned(true);
DATA_SOURCE.setDefaultAutoCommit(true);
}
getConnection() 先從 ThreadLocal 取得連線,若無則從池取得並綁定;closeConnection() 關閉並移除 ThreadLocal,確保執行緒隔離與連線正確歸還。
public static synchronized void update(int thlsh, String ltnr) {
Connection conn = getConnection();
PreparedStatement pstmt = null;
String sql = "update t_wx_ltnrk b set b.LTNR = ? where b.lsh = (select a.ltlsh from t_zxthlsk a where a.lsh = ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setBlob(1, new ByteArrayInputStream(ltnr.getBytes()));
pstmt.setInt(2, thlsh);
pstmt.executeUpdate();
// finally 區塊關閉 pstmt、conn 並移除 ThreadLocal
}
示範 Blob 寫入、子查詢更新、資源釋放完整流程。
finally 關閉 Statement、Connection 並 ThreadLocal.remove()validationQuery 或啟用 testOnBorrowMaxTotal、MaxWaitMillisremoveAbandonedOnBorrow 配合 LogAbandoned 監控長時間未釋放連線本文提供從零建構 DBCP2 連線池的完整範例,涵蓋設定檔管理、工具類封裝、連線池參數調校、ThreadLocal 執行緒綁定與實戰 DAO 操作。掌握這些核心概念,即可在生產環境穩定運作高併發資料庫存取層。