雖然現在用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(" 資料庫連接配接池建立成功! ");
}
@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(" 資料庫連接配接己建立 ......");
}
}
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;
}
}
}
=======================================
這個例子是根據POSTGRESQL資料庫寫的,
請用的時候根據實際的資料庫調整。
調用方法如下:
① ConnectionPool connPool
= new ConnectionPool("org.postgresql.Driver"
,"jdbc:postgresql://dbURI:5432/DBName"
,"postgre"
,"postgre");
② connPool .createPool();
Connection conn = connPool .getConnection();