import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
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() {
}
/**
*
* 構造函數
*
* @param jdbcDriver
* String JDBC 驅動類串
* @param dbUrl
* String 資料庫 URL
* @param dbUsername
* String 連接配接資料庫使用者名
* @param dbPassword
* String 連接配接資料庫使用者的密碼
*/
public ConnectionPool(String jdbcDriver, String dbUrl, String dbUsername,
String dbPassword) {
this.jdbcDriver = jdbcDriver;
this.dbUrl = dbUrl;
this.dbUsername = dbUsername;
this.dbPassword = dbPassword;
}
/**
* 建立一個資料庫連接配接池,連接配接池中的可用連接配接的數量采用類成員 initialConnections 中設定的值
*/
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(" 資料庫連接配接池建立成功! ");
}
/**
*
* 建立由 numConnections 指定數目的資料庫連接配接 , 并把這些連接配接
*
* 放入 connections 向量中
*
*
*
* @param numConnections
* 要建立的資料庫連接配接的數目
*
*/
@SuppressWarnings("unchecked")
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(" 資料庫連接配接己建立 ......");
}
}
/**
*
* 建立一個新的資料庫連接配接并傳回它
*
*
*
* @return 傳回一個新建立的資料庫連接配接
*
*/
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; // 傳回建立的新的資料庫連接配接
}
/**
*
* 通過調用 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(incrementalConnections);
// 重新從池中查找是否有可用連接配接
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();
ResultSet rs = stmt.executeQuery("select count(*) from "
+ testTable);
rs.next();
System.out.println(testTable + ":表的記錄數為:" + rs.getInt(1));
}
} catch (SQLException e) {
// 上面抛出異常,此連接配接己不可用,關閉它,并傳回 false;
e.printStackTrace();
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) {
}
}
/**
* 傳回連接配接池的初始大小
*
* @return 初始連接配接池中可獲得的連接配接數量
*/
public int getInitialConnections() {
return this.initialConnections;
}
/**
* 設定連接配接池的初始大小
*
* @param 用于設定初始連接配接池中連接配接的數量
*/
public void setInitialConnections(int initialConnections) {
this.initialConnections = initialConnections;
}
/**
* 傳回連接配接池自動增加的大小 、
*
* @return 連接配接池自動增加的大小
*/
public int getIncrementalConnections() {
return this.incrementalConnections;
}
/**
* 設定連接配接池自動增加的大小
*
* @param 連接配接池自動增加的大小
*/
public void setIncrementalConnections(int incrementalConnections) {
this.incrementalConnections = incrementalConnections;
}
/**
* 傳回連接配接池中最大的可用連接配接數量
*
* @return 連接配接池中最大的可用連接配接數量
*/
public int getMaxConnections() {
return this.maxConnections;
}
/**
* 設定連接配接池中最大可用的連接配接數量
*
* @param 設定連接配接池中最大可用的連接配接數量值
*/
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
/**
* 擷取測試資料庫表的名字
*
* @return 測試資料庫表的名字
*/
public String getTestTable() {
return this.testTable;
}
/**
* 設定測試表的名字
*
* @param testTable
* String 測試表的名字
*/
public void setTestTable(String testTable) {
this.testTable = testTable;
}
/**
* 内部使用的用于儲存連接配接池中連接配接對象的類
*
* 此類中有兩個成員,一個是資料庫的連接配接,另一個是訓示此連接配接是否
*
* 正在使用的标志。
*/
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;
}
}
}