top
Loading...
Servlet中jdbc應用高級篇(四)

DBConnetionManager的構造函數是私有函數,以避免其他類創建其實例。

private DBConnectionManager() {

init();

}

DBConnetionManager的客戶調用getInstance()方法來得到該類的單一實例的引用。

static synchronized public DBConnectionManager getInstance() {

if (instance == null) {

instance = new DBConnectionManager();

}

clients++;

return instance;

}

單一的實例在第一次調用時創建,以后的調用返回該實例的靜態應用。一個計數器紀錄所有的客戶數,直到客戶釋放引用。這個計數器在以后用來協調關閉連接池。


一、初始化

構造函數調用一個私有的init()函數初始化對象。

private void init() {

InputStream is = getClass().getResourceAsStream("/db.properties");

Properties dbProps = new Properties();

try {

dbProps.load(is);

}

catch (Exception e) {

System.err.println("Can not read the properties file. " +

"Make sure db.properties is in the CLASSPATH");

return;

}

String logFile = dbProps.getProperty("logfile",

"DBConnectionManager.log");

try {

log = new PrintWriter(new FileWriter(logFile, true), true);

}

catch (IOException e) {

System.err.println("Can not open the log file: " + logFile);

log = new PrintWriter(System.err);

}

loadDrivers(dbProps);

createPools(dbProps);

}

方法getResourceAsStream()是一個標準方法,用來打開一個外部輸入文件。文件的位置取決于類加載器,而標準的類加載器從classpath開始搜索。Db.properties文件是一個Porperties格式的文件,保存在連接池中定義的key-value對。下面一些常用的屬性可以定義:

drivers 以空格分開的jdbc驅動程序的列表

logfile 日志文件的絕對路徑

每個連接池中還使用另一些屬性。這些屬性以連接池的名字開頭:

.url數據庫的JDBC URL

.maxconn最大連接數。0表示無限。

.user連接池的用戶名

.password相關的密碼

url屬性是必須的,其他屬性可選。用戶名和密碼必須和所定義的數據庫匹配。

下面是windows平臺下的一個db.properties文件的例子。有一個InstantDB連接池和一個通過odbc連接的access數據庫的數據源,名字叫demo。

drivers=sun.jdbc.odbc.JdbcOdbcDriver jdbc.idbDriver

logfile=D:\user\src\java\DBConnectionManager\log.txt

idb.url=jdbc:idb:c:\local\javawebserver1.1\db\db.prp

idb.maxconn=2

access.url=jdbc:odbc:demo

access.user=demo

access.password=demopw

注意,反斜線在windows平臺下必須雙寫。

初始化方法init()創建一個Porperties對象并裝載db.properties文件,然后讀取日志文件屬性。如果日志文件沒有命名,則使用缺省的名字DBConnectionManager.log在當前目錄下創建。在此情況下,一個系統錯誤被紀錄。

方法loadDrivers()將指定的所有jdbc驅動程序注冊,裝載。

private void loadDrivers(Properties props) {

String driverClasses = props.getProperty("drivers");

StringTokenizer st = new StringTokenizer(driverClasses);

while (st.hasMoreElements()) {

String driverClassName = st.nextToken().trim();

try {

Driver driver = (Driver)

Class.forName(driverClassName).newInstance();

DriverManager.registerDriver(driver);

drivers.addElement(driver);

log("Registered JDBC driver " + driverClassName);

}

catch (Exception e) {

log("Can not register JDBC driver: " +

driverClassName + ", Exception: " + e);

}

}

}

loadDrivers()使用StringTokenizer將dirvers屬性分成單獨的driver串,并將每個驅動程序裝入java虛擬機。驅動程序的實例在JDBC 的DriverManager中注冊,并加入一個私有的向量drivers中。向量drivers用來關閉和注銷所有的驅動程序。

然后,DBConnectionPool對象由私有方法createPools()創建。

private void createPools(Properties props) {

Enumeration propNames = props.propertyNames();

while (propNames.hasMoreElements()) {

String name = (String) propNames.nextElement();

if (name.endsWith(".url")) {

String poolName = name.substring(0, name.lastIndexOf("."));

String url = props.getProperty(poolName + ".url");

if (url == null) {

log("No URL specified for " + poolName);

continue;

}

String user = props.getProperty(poolName + ".user");

String password = props.getProperty(poolName + ".password");

String maxconn = props.getProperty(poolName + ".maxconn", "0");

int max;

try {

max = Integer.valueOf(maxconn).intValue();

}

catch (NumberFormatException e) {

log("Invalid maxconn value " + maxconn + " for " +

poolName);

max = 0;

}

DBConnectionPool pool =

new DBConnectionPool(poolName, url, user, password, max);

pools.put(poolName, pool);

log("Initialized pool " + poolName);

}

}

}

一個枚舉對象保存所有的屬性名,如果屬性名帶有.url結尾,則表示是一個連接池對象需要被實例化。創建的連接池對象保存在一個Hashtable實例變量中。連接池名字作為索引,連接池對象作為值。

二、得到和返回連接

DBConnectionManager提供getConnection()方法和freeConnection方法,這些方法有客戶程序使用。所有的方法以連接池名字所參數,并調用特定的連接池對象。

public Connection getConnection(String name) {

DBConnectionPool pool = (DBConnectionPool) pools.get(name);

if (pool != null) {

return pool.getConnection();

}

return null;

}



public Connection getConnection(String name, long time) {

DBConnectionPool pool = (DBConnectionPool) pools.get(name);

if (pool != null) {

return pool.getConnection(time);

}

return null;

}

public void freeConnection(String name, Connection con) {

DBConnectionPool pool = (DBConnectionPool) pools.get(name);

if (pool != null) {

pool.freeConnection(con);

}

}

三、關閉

最后,由一個release()方法,用來完好地關閉連接池。每個DBConnectionManager客戶必須調用getInstance()方法引用。有一個計數器跟蹤客戶的數量。方法release()在客戶關閉時調用,技術器減1。當最后一個客戶釋放,DBConnectionManager關閉所有的連接池。

List 11-14

public synchronized void release() {

// Wait until called by the last client

if (--clients != 0) {

return;

}



Enumeration allPools = pools.elements();

while (allPools.hasMoreElements()) {

DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();

pool.release();

}

Enumeration allDrivers = drivers.elements();

while (allDrivers.hasMoreElements()) {

Driver driver = (Driver) allDrivers.nextElement();

try {

DriverManager.deregisterDriver(driver);

log("Deregistered JDBC driver " + driver.getClass().getName());

}

catch (SQLException e) {

log(e, "Can not deregister JDBC driver: " +

driver.getClass().getName());

}

}

}

當所有連接池關閉,所有jdbc驅動程序也被注銷。



作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
北斗有巢氏 有巢氏北斗