本文執行個體講述了Java實現資料庫連接池的方法。分享給大家供大家參考。具體如下:
package com.kyo.connection;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 ConnectionParam param; private String testTable = ""; // 測試連接是否可用的測試表名,預設沒有測試表 private Vector connections = null; // 存放串連池中資料庫連接的向量 , 初始時為 // null,它中存放的對象為PooledConnection 型 public void setParam(ConnectionParam param) { this.param = param; } public ConnectionParam getParam() { return param; } /** * 建構函式 * * @param param */ public ConnectionPool(ConnectionParam param) { this.param = param; } /** * * 擷取測試資料庫表的名字 * * @return 測試資料庫表的名字 */ public String getTestTable() { return this.testTable; } /** * * 設定測試表的名字 * * @param testTable * String 測試表的名字 */ public void setTestTable(String testTable) { this.testTable = testTable; } /** * 建立一個資料庫連接池,串連池中的可用串連的數量採用類成員 initialConnections 中設定的值 */ public synchronized void createPool() throws Exception { // 確保串連池沒有建立 // 如果串連池己經建立了,儲存串連的向量 connections 不會為空白 if (connections != null) { return; // 如果己經建立,則返回 } // 執行個體化 JDBC Driver 中指定的驅動類執行個體 Driver driver = (Driver) (Class.forName(this.param.getDriver()) .newInstance()); DriverManager.registerDriver(driver); // 註冊 JDBC 驅動程式 // 建立儲存串連的向量 , 初始時有 0 個元素 connections = new Vector(); // 根據 initialConnections 中設定的值,建立串連。 createConnections(this.param.getMinConnection()); System.out.println(" 資料庫連接池建立成功! "); } /** * * 建立由 numConnections 指定數目的資料庫連接 , 並把這些串連 放入 connections 向量中 * * @param numConnections * 要建立的資料庫連接的數目 */ private void createConnections(int numConnections) throws SQLException { // 迴圈建立指定數目的資料庫連接 for (int x = 0; x < numConnections; x++) { // 是否串連池中的資料庫連接的數量己經達到最大?最大值由類成員 maxConnections,指出,如果 maxConnections // 為 0 或負數,表示串連數量沒有限制。 // 如果串連數己經達到最大,即退出。 if (this.param.getMaxConnection() > 0 && this.connections.size() >= this.param.getMaxConnection()) { 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(" 資料庫連接己建立 ......"); } } /** * * 建立一個新的資料庫連接並返回它 * * @return 返回一個新建立的資料庫連接 */ private Connection newConnection() throws SQLException { // 建立一個資料庫連接 Connection conn = DriverManager.getConnection(this.param.getUrl(), this.param.getUser(), this.param.getPassword()); // 如果這是第一次建立資料庫連接,即檢查資料庫,獲得此資料庫允許支援的 // 最大客戶串連數目 // connections.size()==0 表示目前沒有串連己被建立 if (connections.size() == 0) { DatabaseMetaData metaData = conn.getMetaData(); int driverMaxConnections = metaData.getMaxConnections(); // 資料庫返回的 driverMaxConnections 若為 0 ,表示此資料庫沒有最大 // 串連限制,或資料庫的最大串連限制不知道 // driverMaxConnections 為返回的一個整數,表示此資料庫允許客戶串連的數 目 // 如果串連池中設定的最大串連數量大於資料庫允許的串連數目 , 則置串連池 的最大 // 串連數目為資料庫允許的最大數目 if (driverMaxConnections > 0 && this.param.getMaxConnection() > driverMaxConnections) { this.param.setMaxConnection(driverMaxConnections); } } return conn; // 返回建立的新的資料庫連接 } /** * * 通過調用 getFreeConnection() 函數返回一個可用的資料庫連接 , * * 如果當前沒有可用的資料庫連接,並且更多的資料庫連接不能創 * * 建(如串連池大小的限制),此函數等待一會再嘗試擷取。 * * @return 返回一個可用的資料庫連接對象 */ 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;// 返回獲得的可用的串連 } /** * * 本函數從串連池向量 connections 中返回一個可用的的資料庫連接,如果 * * 當前沒有可用的資料庫連接,本函數則根據 incrementalConnections 設定 * * 的值建立幾個資料庫連接,並放入串連池中。 * * 如果建立後,所有的串連仍都在使用中,則返回 null * * @return 返回一個可用的資料庫連接 */ private Connection getFreeConnection() throws SQLException { // 從串連池中獲得一個可用的資料庫連接 Connection conn = findFreeConnection(); if (conn == null) { // 如果目前串連池中沒有可用的串連 // 建立一些串連 createConnections(this.param.getIncrementalConnections()); // 重新從池中尋找是否有可用串連 conn = findFreeConnection(); if (conn == null) { // 如果建立串連後仍獲得不到可用的串連,則返回 null return null; } } return conn; } /** * * 尋找串連池中所有的串連,尋找一個可用的資料庫連接, * * 如果沒有可用的串連,返回 null * * @return 返回一個可用的資料庫連接 */ 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;// 返回找到到的可用串連 } /** * * 測試一個串連是否可用,如果不可用,關掉它並返回 false * * 否則可用返回 true * * * * @param conn * 需要測試的資料庫連接 * * @return 返回 true 表示此串連可用, false 表示不可用 */ 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; } /** * * 此函數返回一個資料庫連接到串連池中,並把此串連置為空白閑。 * * 所有使用串連池獲得的資料庫連接均應在不使用此串連時返回它。 * * @param 需返回到串連池中的連線物件 */ 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; } /** * * 關閉一個資料庫連接 * * @param 需要關閉的資料庫連接 */ private void closeConnection(Connection conn) { try { conn.close(); } catch (SQLException e) { System.out.println(" 關閉資料庫連接出錯: " + e.getMessage()); } } /** * * 使程式等待給定的毫秒數 * * @param 給定的毫秒數 */ 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; } }}
希望本文所述對大家的java程式設計有所協助。