Connection Pool (1)
(史帝芬, idealist@gcn.net.tw, 2003/09/19)
用Connection Pool存取資料庫可以減少建立Connection的時間,struts1.0.2原本提供一個名為GenericDataSource的class 可以用來建立Connection Pool,在struts 1.1時將它廢棄了,原因是現在的資料庫附的Driver多半已經提供了DataSource,而且,使用資料庫提供的DataSource建立的Connection Pool更穩固!在Oracle中提供的是 OracleConnectionPoolDataSource,我用這個DataSource建立了一個Connection Pool,原始碼如下。(參考JSP教學手冊)
ConnectionPool.java
package tw.idv.idealist.db;
import java.sql.SQLException;
import java.sql.Connection;
import javax.sql.DataSource;
public class ConnectionPool {
private DataSource ds;
private static ConnectionPool mySelf;
private ConnectionPool(DataSource ds) {
this.ds = ds;
}
protected static void init(DataSource ds) {
mySelf = new ConnectionPool(ds);
}
public static ConnectionPool getIstance() {
if (mySelf == null) {
throw new IllegalStateException("Pool not initialized.");
}
return mySelf;
}
public Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
DBInitServlet.java
/*
設為container啟動時啟動
*/
package tw.idv.idealist.db;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.sql.SQLException;
import java.sql.Connection;
import javax.sql.DataSource;
import oracle.jdbc.pool.*;
import java.io.*;
import java.util.*;
public class DBInitServlet extends HttpServlet implements Servlet {
public void destroy() {
super.destroy();
}
public void init() throws ServletException {
super.init();
try {
InputStream is = getClass().getResourceAsStream("/tw/idv/idealist/resources/Database.properties");
Properties p = new Properties();
p.load(is);
OracleDataSource ds = new OracleConnectionPoolDataSource ();
ds.setDriverType(p.getProperty("oracle.drivertype"));
ds.setServerName(p.getProperty("oracle.server"));
ds.setPortNumber(Integer.parseInt(p.getProperty("oracle.port")));
ds.setDatabaseName(p.getProperty("oracle.database"));
ds.setUser(p.getProperty("oracle.user"));
ds.setPassword(p.getProperty("oracle.password"));
ConnectionPool.init(ds);
is.close();
} catch (SQLException e) {
e.printStackTrace();
throw new ServletException("Unable to open datasource.");
}
catch (IOException ie) {
ie.printStackTrace();
throw new ServletException("Unable to open datasource.");
}
}
}
Database.properties
oracle.drivertype=thin
oracle.server=dbserver
oracle.port=1521
oracle.database=db3
oracle.user=test
oracle.password=pwd