📄 dbconnectionmanager.java
字号:
package dbpool;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;
//import javax.servlet.ServletConfig;
public class DBConnectionManager{
static private DBConnectionManager instance; // 唯一实例
static private int clients; //连接数
private Vector drivers = new Vector();//驱动
private PrintWriter log;//日志
private Hashtable pools = new Hashtable();//连接池
private String fileName="db.properties";//属性配置文件
FileWriter logFW=null;
PrintWriter logPW=null;
String logFileName ="";
File logFile=null;
static int connectionCounter=0; //连接计数器
/**
* 返回唯一实例.如果是第一次调用此方法,则创建实例
*
* @return DBConnectionManager 唯一实例
*/
static synchronized public DBConnectionManager getInstance() {
if (instance == null) {
instance = new DBConnectionManager();
}
clients++;
return instance;
}
/**
* 重新初始化
*
* @return DBConnectionManager 唯一实例
*/
synchronized public void reset() {
if (instance != null) {
instance = null;
release();
instance = new DBConnectionManager();
clients++;
log("连接池被初始化。");
}
}
/**
* 不创建任何实例
*
* @return DBConnectionManager
*/
static public DBConnectionManager getDocInstance() {
return instance;
}
/**
* 建构函数私有以防止其它对象创建本类实例
*/
private DBConnectionManager() {
init();
}
/**
* 将连接对象返回给由名字指定的连接池
*
* @param name 在属性文件中定义的连接池名字
* @param con 连接对象
*/
public void freeConnection(String name, Connection con) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
pool.freeConnection(con);
}
}
/**
* 获得一个可用的(空闲的)连接.如果没有可用连接,且已有连接数小于最大连接数
* 限制,则创建并返回新连接
*
* @param name 在属性文件中定义的连接池名字
* @return Connection 可用连接或null
*/
public Connection getConnection(String name) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
return pool.getConnection();
}
return null;
}
/**
* 获得一个可用连接.若没有可用连接,且已有连接数小于最大连接数限制,
* 则创建并返回新连接.否则,在指定的时间内等待其它线程释放连接.
*
* @param name 连接池名字
* @param time 以毫秒计的等待时间
* @return Connection 可用连接或null
*/
public Connection getConnection(String name, long time) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
return pool.getConnection(time);
}
return null;
}
/**
* 关闭所有连接,撤销驱动程序的注册
*/
public synchronized void release() {
// 等待直到最后一个客户程序调用
// 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("撤销JDBC驱动程序 " + driver.getClass().getName()+"的注册");
}
catch (SQLException e) {
log(e, "无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName());
}
}
}
//用来调入修改过的数据库参数,从而不用重启动tomcat
public void loadURL( String name){
release();
init();
/**
Enumeration allPools = pools.elements();
while (allPools.hasMoreElements()) {
DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
pool.release();
}
try {
InputStream is = new FileInputStream(fileName);
Properties dbProps = new Properties();
dbProps.load(is);
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
String url = dbProps.getProperty(name+".url")+dbProps.getProperty(name+".host")+"/"+
dbProps.getProperty(name+".dbName")+"?useUnicode=true&characterEncoding="+
dbProps.getProperty(name+".character");
if( (props.getProperty("driver")).indexOf("oracle")>=0)
url = dbProps.getProperty(name+".url")+dbProps.getProperty(name+".host")+":"+
dbProps.getProperty(name+".dbName");
pool.setURL(url);
}
catch (Exception e) {
System.err.println("不能读取属性文件. " +"请确保db.properties在CLASSPATH指定的路径中");
}
**/
}
/**
* 根据指定属性创建连接池实例.
*
* @param props 连接池属性
*/
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");
String url = props.getProperty(poolName+".url")+props.getProperty(poolName+".host")+"/"+
props.getProperty(poolName+".dbName")+"?useUnicode=true&characterEncoding="+
props.getProperty(poolName+".character");
if( (props.getProperty("driver")).indexOf("oracle")>=0)
url = props.getProperty(poolName+".url")+props.getProperty(poolName+".host")+":"+
props.getProperty(poolName+".dbName");
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,dbInfo, max);
DBConnectionPool pool = new DBConnectionPool(poolName, url,user,password, max);
pools.put(poolName, pool);
log("成功创建连接池" + poolName);
}//end if
}//end while
}
/**
* 读取属性完成初始化
*/
private void init() {
try{
//下面这种调用,配置文件被缓存,只有重启tomcat才会调用新的文件 改为new FileInputStream()方式可再次调用
//InputStream is = getClass().getResourceAsStream(fileName);
String path=(((this.getClass()).getResource("")).getPath()).toString();
//path 形如:/D:/100imserver/Tomcat5.5/webapps/ROOT/WEB-INF/classes/dbpool/
//配置文件存放在../config目录下
path=path.substring(0,path.indexOf("WEB-INF"));
InputStream is = new FileInputStream(path+"config/"+fileName);//
Properties dbProps = new Properties();
try {
dbProps.load(is);
is.close();
}
catch (Exception e) {
System.err.println("不能读取属性文件. " +"请确保db.properties在CLASSPATH指定的路径中");
try{is.close(); }catch(Exception ee){}
return;
}
//数据库日志文件存放在../logs目录下
logFileName = path+"logs/"+dbProps.getProperty("logfile");
loadDrivers(dbProps);
createPools(dbProps);
}catch(Exception ee){}
}
/**
* 装载和注册所有JDBC驱动程序
*
* @param props 属性
*/
private void loadDrivers(Properties props) {
String driverClasses = props.getProperty("driver");
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) {
log("无法注册JDBC驱动程序: " +
driverClassName + ", 错误: " + e);
}
}
}
/**
* 将文本信息写入日志文件
*/
private void log(String msg) {
// log.println(new Date() + ": " + msg);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -