|
Posted on 2009-09-02 23:01 Gavin.lee 阅读(2313) 评论(0) 编辑 收藏 所属分类: JDBC
其实以下这个完全可以用java现成的连接池来做,只是需要在服务端配置数据源,在java中依据不同的name去lookup,个人只是觉得麻烦,从网上查了些资料,整理了一个现在符合我目前项目的自制连接池····
经过一段时间的试用,该连接池适用于中小型系统,详细如下:
自定义连接池管理类DBConnectionManager.java:
package yixun.wap.db;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
/** *//**
* 功能:一个实例对应多个连接池,一个连接池对应多个连接
* 设计:单例,内部类实现
* 实现:一个实例,一个HashTable内有多个池,每个池包含了一个Vector列表,列表内存放自由连接
* @author 显武
* @date 2009-12-4 22:33:57
*
*/
public class DBConnectionManager {
private static int clientLinks;
private Vector<Driver> drivers = new Vector<Driver>();
private PrintWriter logOut;
private Hashtable<String, DBConnectionPool> pools = new Hashtable<String, DBConnectionPool>();
//单例
private DBConnectionManager() {
System.out.println("init");
init();
}
public static DBConnectionManager instance; // 唯一实例
public static synchronized DBConnectionManager getInstance() {
if (instance == null) {
instance = new DBConnectionManager();
}
clientLinks++;
return instance;
}
/** *//**
* 读取属性完成初始化
*/
private void init() {
InputStream is = getClass().getResourceAsStream("/dbPools.properties");
Properties dbProps = new Properties();
try {
dbProps.load(is);
} catch (Exception e) {
System.err.println("不能读取属性文件.请确保dbPools.properties在CLASSPATH指定的路径中");
return;
}
String logFile = dbProps.getProperty("logfile", "DBConnectionManager.log");
try {
logOut = new PrintWriter(new FileWriter(logFile, true), true);
} catch (IOException e) {
System.err.println("无法打开日志文件: " + logFile);
logOut = new PrintWriter(System.err);
}
loadDrivers(dbProps);
createPools(dbProps);
}
/** *//**
* 装载和注册所有JDBC驱动程序
*
* @param props属性
*/
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("成功注册JDBC驱动程序" + driverClassName);
} catch (Exception e) {
e.printStackTrace();
log("无法注册JDBC驱动程序: " + driverClassName + ", 错误: " + e);
}
}
}
/** *//**
* 根据指定属性创建连接池实例.
*
* @param props
* 连接池属性 113
*/
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("没有为连接池" + poolName + "指定URL");
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("错误的最大连接数限制: " + maxconn + " .连接池: " + poolName);
max = 0;
}
DBConnectionPool pool = new DBConnectionPool(poolName, url, user, password, max);
pools.put(poolName, pool);
log("成功创建连接池" + poolName);
}
}
}
/** *//**
* 将连接对象返回给由名字指定的连接池
* @param pooName
* 在属性文件中定义的连接池名字
* @param con
* 连接对象\\\\r
*/
public void freeConnection(String pooName, Connection con) {
DBConnectionPool pool = (DBConnectionPool) pools.get(pooName);
if (pool != null) {
pool.freeConnection(con);
}
}
/** *//**
* 获得一个可用的(空闲的)连接.如果没有可用连接,且已有连接数小于最大连接数 053 * 限制,则创建并返回新连
* @param name
* 在属性文件中定义的连接池名字 056 *
* @return Connection
* 可用连接或null 057
*/
public Connection getConnection(String pooName) {
DBConnectionPool pool = (DBConnectionPool) pools.get(pooName);
if (pool != null) {
return pool.getConnection();
}
return null;
}
/** *//**
* 获得一个可用连接.若没有可用连接,且已有连接数小于最大连接数限制,
* 则创建并返回新连接.否则,在指定的时间内等待其它线程释放连接.
*
* @param name
* 连接池名字 071 *
* @param time
* 以毫秒计的等待时间\\\\r
* @return Connection
* 可用连接或null
*/
public Connection getConnection(String poolName, long time) {
DBConnectionPool pool = (DBConnectionPool) pools.get(poolName);
if (pool != null) {
return pool.getConnection(time);
}
return null;
}
/** *//**
* 关闭所有连接,撤销驱动程序的注册\\\\r
*/
public synchronized void release() {
// 等待直到最后一个客户程序调用
if (--clientLinks != 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("撤销JDBC驱动程序 " + driver.getClass().getName() + "的注册");
} catch (SQLException e) {
log(e, "无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName());
}
}
}
/** *//**
* 将文本信息写入日志文件
*/
private void log(String msg) {
logOut.println(new Date() + ": " + msg);
}
/** *//**
* 将文本信息与异常写入日志文件
*/
private void log(Throwable e, String msg) {
logOut.println(new Date() + ": " + msg);
e.printStackTrace(logOut);
}
/** *//**
* 此内部类定义了一个连接池.它能够根据要求创建新连接,直到预定的最\\\\r
*/
class DBConnectionPool {
private int checkedOut;
private Vector<Connection> freeConnections = new Vector<Connection>();
private int maxConn;
private String poolName;
private String password;
private String URL;
private String user;
/** *//**
* 创建新的连接池
*
* @param poolName
* 连接池名字
* @param URL
* 数据库的JDBC URL
* @param user
* 数据库帐号,或 null
* @param password
* 密码,或 null
* @param maxConn
* 此连接池允许建立的最大连接数
*/
public DBConnectionPool(String poolName, String URL, String user,
String password, int maxConn) {
this.poolName = poolName;
this.URL = URL;
this.user = user;
this.password = password;
this.maxConn = maxConn;
}
/** *//**
* 将不再使用的连接返回给连接池
*
* @param con客户程序释放的连接
*/
public synchronized void freeConnection(Connection con) {
// 将指定连接加入到向量末尾
freeConnections.addElement(con);
checkedOut--;
notifyAll();
}
/** *//**
* 从连接池获得一个可用连接.如没有空闲的连接且当前连接数小于最大连接 数限制,则创建新连接.
* 如原来登记为可用的连接不再有效,则从向量删除之, 然后递归调用自己以尝试新的可用连接.
*/
public synchronized Connection getConnection() {
Connection con = null;
if (freeConnections.size() > 0) {// 获取向量中第一个可用连接
con = (Connection) freeConnections.firstElement();
freeConnections.removeElementAt(0);
try {
if (con.isClosed()) {
log("从连接池" + poolName + "删除一个无效连接");
// 递归调用自己,尝试再次获取可用连接
con = getConnection();
}
} catch (SQLException e) {
log("从连接池" + poolName + "删除一个无效连接");
// 递归调用自己,尝试再次获取可用连接
con = getConnection();
}
} else if (maxConn == 0 || checkedOut < maxConn) {
con = newConnection();
}
if (con != null) {
checkedOut++;
}
return con;
}
/** *//**
* 从连接池获取可用连接.可以指定客户程序能够等待的最长时间 参见前一个getConnection()方法.
*
* @param timeout
* 以毫秒计的等待时间限制
*/
public synchronized Connection getConnection(long timeout) {
long startTime = new Date().getTime();
Connection con;
while ((con = getConnection()) == null) {
try {
wait(timeout);
} catch (InterruptedException e) {
e.printStackTrace();
}
if ((new Date().getTime() - startTime) >= timeout) {// wait()返回的原因是超时
return null;
}
}
return con;
}
/** *//**
* 关闭所有连接
*/
public synchronized void release() {
Enumeration allConnections = freeConnections.elements();
while (allConnections.hasMoreElements()) {
Connection con = (Connection) allConnections.nextElement();
try {
con.close();
log("关闭连接池" + poolName + "中的一个连接");
} catch (SQLException e) {
log(e, "无法关闭连接池" + poolName + "中的连接");
e.printStackTrace();
}
}
freeConnections.removeAllElements();
}
/** *//**
* 创建新的连接
*/
private Connection newConnection() {
Connection con = null;
try {
if (user == null || "".equals(user)) {
con = DriverManager.getConnection(URL);
} else {
con = DriverManager.getConnection(URL, user, password);
}
log("连接池" + poolName + "创建一个新的连接");
} catch (SQLException e) {
log(e, "无法创建下列URL的连接: " + URL);
return null;
}
return con;
}
}
}
连接池使用实例DBConnection.java:
package yixun.wap.db;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
//import java.sql.Types;
/** *//**
*
* @author 显武
* @date 2009-12-4 22:32:52
*
*/
public class DBConnection {
private DBConnectionManager connMgr = null;
private Connection conn = null;
private PreparedStatement prepStmt = null;
private ResultSet rs = null;
public CallableStatement cstmt;
public String poolName = "";
/** *//**
* 执行SQL
*
* @param poolName
* @param sql
* @throws SQLException
*/
public DBConnection(String poolName, String sql) throws SQLException {
this.poolName = poolName;
connMgr = DBConnectionManager.getInstance();
this.conn = connMgr.getConnection(poolName);
prepStmt = conn.prepareStatement(sql);
}
/** *//**
* 执行存储过程
*
* @param poolName
* @throws SQLException
*/
public DBConnection(String poolName) throws SQLException {
this.poolName = poolName;
connMgr = DBConnectionManager.getInstance();
this.conn = connMgr.getConnection(poolName);
}
public Connection getConnection() {
return connMgr.getConnection(poolName);
}
public PreparedStatement getPreparedStatement() {
return prepStmt;
}
public ResultSet executeQuery() throws SQLException {
return this.prepStmt.executeQuery();
}
public boolean execute() throws SQLException {
return this.prepStmt.execute();
}
public int executeUpdate() throws SQLException {
return this.prepStmt.executeUpdate();
}
/** *//**
* 有返回值的存储过程执行
*
* @param procName
* @param params
* @return
* @throws SQLException
*/
public ResultSet executeQueryProcedure(String procName, Object[] params) throws SQLException {
int index = 0;
cstmt = conn.prepareCall(procName);
for (Object obj : params) {
index++;
cstmt.setObject(index, obj);
}
// cstmt.registerOutParameter(3, Types.INTEGER);
rs = cstmt.executeQuery();
return rs;
}
/** *//**
* 返回boolean的存储过程
*
* @param procName
* @param params
* @return
* @throws SQLException
*/
public boolean executeProcedure(String procName, Object[] params) throws SQLException {
boolean flag = false;
int index = 0;
cstmt = conn.prepareCall(procName);
for (Object obj : params) {
index++;
cstmt.setObject(index, obj == null ? "" : obj);
}
flag = cstmt.execute();
return flag;
}
public void setString(int index, String value) throws SQLException {
prepStmt.setString(index, value);
}
public void setInt(int index, int value) throws SQLException {
prepStmt.setInt(index, value);
}
public void setBoolean(int index, boolean value) throws SQLException {
prepStmt.setBoolean(index, value);
}
public void setDate(int index, Date value) throws SQLException {
prepStmt.setDate(index, value);
}
public void setLong(int index, long value) throws SQLException {
prepStmt.setLong(index, value);
}
public void setFloat(int index, float value) throws SQLException {
prepStmt.setFloat(index, value);
}
public void setDouble(int index, double orderAmount) throws SQLException {
prepStmt.setDouble(index, orderAmount);
}
public void setObject(int index, Object obj) throws SQLException {
prepStmt.setObject(index, obj);
}
public void commit() {
try {
conn.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
public void rollback() {
try {
conn.rollback();
} catch (Exception e) {
e.printStackTrace();
}
}
/** *//**
* 释放连接
*
*/
public void free() {
try {
if (this.rs != null) {
this.rs.close();
this.rs = null;
}
if (this.prepStmt != null) {
this.prepStmt.close();
this.prepStmt = null;
}
this.commit();
this.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
// 将用过的连接再回收到池中,在回收连接前,要保证上一连接操作完
connMgr.freeConnection(poolName, this.conn);
}
}
配置文件:
#if you have more DB,please split drivers with blank.
drivers = net.sourceforge.jtds.jdbc.Driver
logfile=D:\\log.txt
newsPool.maxconn = 100
newsPool.url = jdbc:jtds:sqlserver://dbip/dbName
newsPool.user =
newsPool.password =
cpPool.maxconn = 100
cpPool.url = jdbc:jtds:sqlserver://dbip/dbName
cpPool.user =
cpPool.password =
使用:
public List<Forum> getHomeHotForums(int num) {
DBConnection nb = null;
ResultSet rs = null;
String sql = "select top %s * from bbs_posts order by p_click desc";
sql = String.format(sql, num);
List<Forum> forums = null;
try {
forums = new ArrayList<Forum>();
nb = new DBConnection("newsPool", sql);
rs = nb.executeQuery();
while(rs.next()) {
forums.add(this.populate(rs));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
nb.free();
}
return forums;
}
|