一個JAVA數據庫連接池實現源碼
// // 一個效果非常不錯的JAVA數據庫連接池. // from:http://www.jxer.com/home/?uid-195-action-viewspace-itemid-332 // 雖然現在用APACHE COMMONS DBCP可以非常方便的建立數據庫連接池, // 但是像這篇文章把數據庫連接池的內部原理寫的這么透徹,注視這么完整, // 真是非常難得,讓開發人員可以更深層次的理解數據庫連接池,真是非常感 // 謝這篇文章的作者。 // import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Enumeration; import java.util.Vector;public class ConnectionPool {
private String jdbcDriver = ""; // 數據庫驅動 private String dbUrl = ""; // 數據 URL private String dbUsername = ""; // 數據庫用戶名 private String dbPassword = ""; // 數據庫用戶密碼 private String testTable = ""; // 測試連接是否可用的測試表名,默認沒有測試表 private int initialConnections = 10; // 連接池的初始大小 private int incrementalConnections = 5; // 連接池自動增加的大小 private int maxConnections = 50; // 連接池最大的大小 private Vector connections = null; // 存放連接池中數據庫連接的向量 , 初始時為 null
// 它中存放的對象為 PooledConnection 型
public ConnectionPool(String jdbcDriver, String dbUrl, String dbUsername, String dbPassword) { this.jdbcDriver = jdbcDriver; this.dbUrl = dbUrl; this.dbUsername = dbUsername; this.dbPassword = dbPassword; } public int getInitialConnections() { return this.initialConnections; } public void setInitialConnections(int initialConnections) { this.initialConnections = initialConnections; } public int getIncrementalConnections() { return this.incrementalConnections; } public void setIncrementalConnections(int incrementalConnections) { this.incrementalConnections = incrementalConnections; } public int getMaxConnections() { return this.maxConnections; } public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } public String getTestTable() { return this.testTable; } public void setTestTable(String testTable) { this.testTable = testTable; } public synchronized void createPool() throws Exception { // 確保連接池沒有創建 // 假如連接池己經創建了,保存連接的向量 connections 不會為空 if (connections != null) { return; // 假如己經創建,則返回 } // 實例化 JDBC Driver 中指定的驅動類實例 Driver driver = (Driver) (Class.forName(this.jdbcDriver).newInstance()); DriverManager.registerDriver(driver); // 注冊 JDBC 驅動程序 // 創建保存連接的向量 , 初始時有 0 個元素 connections = new Vector(); // 根據 initialConnections 中設置的值,創建連接。 createConnections(this.initialConnections); System.out.println(" 數據庫連接池創建成功! "); } private void createConnections(int numConnections) throws SQLException { // 循環創建指定數目的數據庫連接 for (int x = 0; x < numConnections; x++) { // 是否連接池中的數據庫連接的數量己經達到最大?最大值由類成員 maxConnections // 指出,假如 maxConnections 為 0 或負數,表示連接數量沒有限制。 // 假如連接數己經達到最大,即退出。 if (this.maxConnections > 0 && this.connections.size() >= this.maxConnections) { break; } //add a new PooledConnection object to connections vector // 增加一個連接到連接池中(向量 connections 中) try { connections.addElement(new PooledConnection(newConnection())); } catch (SQLException e) { System.out.println(" 創建數據庫連接失敗! " + e.getMessage()); throw new SQLException(); } System.out.println(" 數據庫連接己創建 ......"); } } private Connection newConnection() throws SQLException { // 創建一個數據庫連接 Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword); // 假如這是第一次創建數據庫連接,即檢查數據庫,獲得此數據庫答應支持的 // 最大客戶連接數目 //connections.size()==0 表示目前沒有連接己被創建 if (connections.size() == 0) { DatabaseMetaData metaData = conn.getMetaData(); int driverMaxConnections = metaData.getMaxConnections(); // 數據庫返回的 driverMaxConnections 若為 0 ,表示此數據庫沒有最大 // 連接限制,或數據庫的最大連接限制不知道 //driverMaxConnections 為返回的一個整數,表示此數據庫答應客戶連接的數目 // 假如連接池中設置的最大連接數量大于數據庫答應的連接數目 , 則置連接池的最大 // 連接數目為數據庫答應的最大數目 if (driverMaxConnections > 0 && this.maxConnections > driverMaxConnections) { this.maxConnections = driverMaxConnections; } } return conn; // 返回創建的新的數據庫連接 } public synchronized Connection getConnection() throws SQLException { // 確保連接池己被創建 if (connections == null) { return null; // 連接池還沒創建,則返回 null } Connection conn = getFreeConnection(); // 獲得一個可用的數據庫連接 // 假如目前沒有可以使用的連接,即所有的連接都在使用中 while (conn == null) { // 等一會再試 wait(250); conn = getFreeConnection(); // 重新再試,直到獲得可用的連接,假如 //getFreeConnection() 返回的為 null // 則表明創建一批連接后也不可獲得可用連接 } return conn; // 返回獲得的可用的連接 } private Connection getFreeConnection() throws SQLException { // 從連接池中獲得一個可用的數據庫連接 Connection conn = findFreeConnection(); if (conn == null) { // 假如目前連接池中沒有可用的連接 // 創建一些連接 createConnections(incrementalConnections); // 重新從池中查找是否有可用連接 conn = findFreeConnection(); if (conn == null) { // 假如創建連接后仍獲得不到可用的連接,則返回 null return null; } } return conn; } private Connection findFreeConnection() throws SQLException { Connection conn = null; PooledConnection pConn = null; // 獲得連接池向量中所有的對象 Enumeration enumerate = connections.elements(); // 遍歷所有的對象,看是否有可用的連接 while (enumerate.hasMoreElements()) { pConn = (PooledConnection) enumerate.nextElement(); if (!pConn.isBusy()) { // 假如此對象不忙,則獲得它的數據庫連接并把它設為忙 conn = pConn.getConnection(); pConn.setBusy(true); // 測試此連接是否可用 if (!testConnection(conn)) { // 假如此連接不可再用了,則創建一個新的連接, // 并替換此不可用的連接對象,假如創建失敗,返回 null try { conn = newConnection(); } catch (SQLException e) { System.out.println(" 創建數據庫連接失敗! " + e.getMessage()); return null; } pConn.setConnection(conn); } break; // 己經找到一個可用的連接,退出 } } return conn; // 返回找到到的可用連接 } private boolean testConnection(Connection conn) { try { // 判定測試表是否存在 if (testTable.equals("")) { // 假如測試表為空,試著使用此連接的 setAutoCommit() 方法 // 來判定連接否可用(此方法只在部分數據庫可用,假如不可用 , // 拋出異常)。注重:使用測試表的方法更可靠 conn.setAutoCommit(true); } else { // 有測試表的時候使用測試表測試 //check if this connection is valid Statement stmt = conn.createStatement(); stmt.execute("select count(*) from " + testTable); } } catch (SQLException e) { // 上面拋出異常,此連接己不可用,關閉它,并返回 false; closeConnection(conn); return false; } // 連接可用,返回 true return true; } public void returnConnection(Connection conn) { // 確保連接池存在,假如連接沒有創建(不存在),直接返回 if (connections == null) { System.out.println(" 連接池不存在,無法返回此連接到連接池中 !"); return; } PooledConnection pConn = null; Enumeration enumerate = connections.elements(); // 遍歷連接池中的所有連接,找到這個要返回的連接對象 while (enumerate.hasMoreElements()) { pConn = (PooledConnection) enumerate.nextElement(); // 先找到連接池中的要返回的連接對象 if (conn == pConn.getConnection()) { // 找到了 , 設置此連接為空閑狀態 pConn.setBusy(false); break; } } } public synchronized void refreshConnections() throws SQLException { // 確保連接池己創新存在 if (connections == null) { System.out.println(" 連接池不存在,無法刷新 !"); return; } PooledConnection pConn = null; Enumeration enumerate = connections.elements(); while (enumerate.hasMoreElements()) { // 獲得一個連接對象 pConn = (PooledConnection) enumerate.nextElement(); // 假如對象忙則等 5 秒 ,5 秒后直接刷新 if (pConn.isBusy()) { wait(5000); // 等 5 秒 } // 關閉此連接,用一個新的連接代替它。 closeConnection(pConn.getConnection()); pConn.setConnection(newConnection()); pConn.setBusy(false); } } public synchronized void closeConnectionPool() throws SQLException { // 確保連接池存在,假如不存在,返回 if (connections == null) { System.out.println(" 連接池不存在,無法關閉 !"); return; } PooledConnection pConn = null; Enumeration enumerate = connections.elements(); while (enumerate.hasMoreElements()) { pConn = (PooledConnection) enumerate.nextElement(); // 假如忙,等 5 秒 if (pConn.isBusy()) { wait(5000); // 等 5 秒 } //5 秒后直接關閉它 closeConnection(pConn.getConnection()); // 從連接池向量中刪除它 connections.removeElement(pConn); } // 置連接池為空 connections = null; } private void closeConnection(Connection conn) { try { conn.close(); } catch (SQLException e) { System.out.println(" 關閉數據庫連接出錯: " + e.getMessage()); } } private void wait(int mSeconds) { try { Thread.sleep(mSeconds); } catch (InterruptedException e) { } } class PooledConnection { Connection connection = null; // 數據庫連接 boolean busy = false; // 此連接是否正在使用的標志,默認沒有正在使用 // 構造函數,根據一個 Connection 構告一個 PooledConnection 對象 public PooledConnection(Connection connection) { this.connection = connection; } // 返回此對象中的連接 public Connection getConnection() { return connection; } // 設置此對象的,連接 public void setConnection(Connection connection) { this.connection = connection; } // 獲得對象連接是否忙 public boolean isBusy() { return busy; } // 設置對象的連接正在忙 public void setBusy(boolean busy) { this.busy = busy; } } public static void main(String[] args) { ConnectionPool connPool = new ConnectionPool("oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:@*.*.*.*" , "name", "password"); try { connPool.createPool(); } catch (Exception ex) { ex.printStackTrace(); } try { Connection conn = connPool.getConnection(); } catch (SQLException ex1) { ex1.printStackTrace(); } }
}</pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!