服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

功能完善的java连接池调用实例


  /**
* title: connectpool.java
* description: 连接池管理器
* copyright: copyright (c) 2002/12/25
* company:
* author :
* version 2.0
*/

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.date;

/**
* 管理类dbconnectionmanager支持对一个或多个由属性文件定义的数据库连接
* 池的访问.客户程序可以调用getinstance()方法访问本类的唯一实例.
*/
public class connectpool
{
static public connectpool instance; // 唯一实例
static public int clients;
public vector drivers = new vector(); //驱动
public printwriter log;
public hashtable pools = new hashtable(); //连接

/**
* 返回唯一实例.如果是第一次调用此方法,则创建实例
*
* @return dbconnectionmanager 唯一实例
*/
static synchronized public connectpool getinstance()
{
if (instance == null)
{
instance = new connectpool();
}

clients++;

return instance;
}

/**
* 建构函数私有以防止其它对象创建本类实例
*/
public connectpool() {
init();
}

/**
* 将连接对象返回给由名字指定的连接池
*
* @param name 在属性文件中定义的连接池名字
* @param con 连接对象
*/
public void freeconnection(string name, connection con)
{
dbconnectionpool pool = (dbconnectionpool) pools.get(name);
if (pool != null)
{
pool.freeconnection(con);
}
else
{
system.out.println("pool ==null");
}
clients--;
}

/**
* 获得一个可用的(空闲的)连接.如果没有可用连接,且已有连接数小于最大连接数
* 限制,则创建并返回新连接
*
* @param name 在属性文件中定义的连接池名字
* @return connection 可用连接或null
*/
public connection getconnection(string name)
{
dbconnectionpool pool = (dbconnectionpool) pools.get(name);
if (pool != null)
{
//return pool.getconnection();
return pool.returnconnection();
}
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());
}
}
}

/**
* 根据指定属性创建连接池实例.
*
* @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");
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);
}
}
}

/**
* 读取属性完成初始化
*/
private void init()
{
try
{
properties p = new properties();
string configs = system.getproperty("user.dir")+"/conf/db.properties";

system.out.println("configs file local at "+configs);
fileinputstream is = new fileinputstream(configs);
properties dbprops = new properties();
try
{
dbprops.load(is);
}
catch (exception e)
{
system.err.println("不能读取属性文件. " +"请确保db.properties在classpath指定的路径中");
return;
}
string logfile = dbprops.getproperty("logfile", "dbconnectionmanager.log");
try{

log = new printwriter(new filewriter(logfile, true), true);
}
catch (ioexception e)
{
system.err.println("无法打开日志文件: " + logfile);
log = new printwriter(system.err);
}
loaddrivers(dbprops);
createpools(dbprops); }catch(exception e){}
}

/**
171 * 装载和注册所有jdbc驱动程序
172 *
173 * @param props 属性
174 */
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);
system.out.println(driverclassname);
log("成功注册jdbc驱动程序" + driverclassname);
}
catch (exception e)
{
log("无法注册jdbc驱动程序: " +
driverclassname + ", 错误: " + e);
}
}
}

/**
* 将文本信息写入日志文件
*/
private void log(string msg)
{
log.println(new date() + ": " + msg);
}

/**
* 将文本信息与异常写入日志文件
*/
private void log(throwable e, string msg)
{
log.println(new date() + ": " + msg);
e.printstacktrace(log);
}

/**
* 此内部类定义了一个连接池.它能够根据要求创建新连接,直到预定的最
* 大连接数为止.在返回连接给客户程序之前,它能够验证连接的有效性.
*/

class dbconnectionpool
{
//private int checkedout;
private vector freeconnections = new vector();
private int maxconn;
private string name;
private string password;
private string url;
private string user;

/**
* 创建新的连接池
*
* @param name 连接池名字
* @param url 数据库的jdbc url
* @param user 数据库帐号,或 null
* @param password 密码,或 null
* @param maxconn 此连接池允许建立的最大连接数
*/
public dbconnectionpool(string name, string url, string user, string password,int maxconn)
{
this.name = name;
this.url = url;
this.user = user;
this.password = password;
this.maxconn = maxconn;
}
/**
* 将不再使用的连接返回给连接池
*
* @param con 客户程序释放的连接
*/
public synchronized void freeconnection(connection con) {
// 将指定连接加入到向量末尾
try
{
if(con.isclosed()){system.out.println("before freeconnection con is closed");}
freeconnections.addelement(con);
connection contest = (connection) freeconnections.lastelement();
if(contest.isclosed()){system.out.println("after freeconnection contest is closed");}
notifyall();
}catch(sqlexception e){system.out.println(e);}
}

/**
* 从连接池获得一个可用连接.如没有空闲的连接且当前连接数小于最大连接
* 数限制,则创建新连接.如原来登记为可用的连接不再有效,则从向量删除之,
* 然后递归调用自己以尝试新的可用连接.
*/
public synchronized connection getconnection()
{
connection con = null;
if (freeconnections.size() > 0)
{
// 获取向量中第一个可用连接
con = (connection) freeconnections.firstelement();
freeconnections.removeelementat(0);
try {
if (con.isclosed())
{
log("从连接池" + name+"删除一个无效连接");
system.out.println("从连接池" + name+"删除一个无效连接");
// 递归调用自己,尝试再次获取可用连接
con = getconnection();
}
}
catch (sqlexception e)
{
log("从连接池" + name+"删除一个无效连接时错误");
system.out.println("从连接池" + name+"删除一个无效连接出错");
// 递归调用自己,尝试再次获取可用连接
con = getconnection();
}
if(freeconnections.size()>maxconn)
{ system.out.println(" 删除一个溢出连接 ");
releaseone();
}
}

else if((maxconn == 0)||(freeconnections.size()<maxconn))
{
con = newconnection();
}

return con;
}

public synchronized connection returnconnection()
{
connection con = null;
//如果闲置小于最大连接,返回一个新连接
if(freeconnections.size()<maxconn)
{
con = newconnection();
}
//如果闲置大于最大连接,返回一个可用的旧连接
else if(freeconnections.size()>=maxconn)
{

con = (connection) freeconnections.firstelement();
system.out.println(" [a 连接池可用连接数 ] : "+"[ "+freeconnections.size()+" ]");
freeconnections.removeelementat(0);
system.out.println(" [b 连接池可用连接数 ] : "+"[ "+freeconnections.size()+" ]");
try
{
if (con.isclosed())
{
log("从连接池" + name+"删除一个无效连接");
system.out.println("从连接池" + name+"删除一个无效连接");
returnconnection();
}
}catch (sqlexception e)
{
log("从连接池" + name+"删除一个无效连接时错误");
system.out.println("从连接池" + name+"删除一个无效连接出错");
returnconnection();
}
}
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) {}
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("关闭连接池" + name+"中的一个连接");
}
catch (sqlexception e)
{
log(e, "无法关闭连接池" + name+"中的连接");
}
}
freeconnections.removeallelements();
}
/**
* 关闭一个连接
*/
public synchronized void releaseone()
{
if(freeconnections.firstelement()!=null)
{ connection con = (connection) freeconnections.firstelement();
try {
con.close();
system.out.println("关闭连接池" + name+"中的一个连接");
log("关闭连接池" + name+"中的一个连接");
}
catch (sqlexception e)
{

system.out.println("无法关闭连接池" + name+"中的一个连接");
log(e, "无法关闭连接池" + name+"中的连接");
}
}
else
{
system.out.println("releaseone() bug.......................................................");

}
}

/**
* 创建新的连接
*/
private connection newconnection()
{
connection con = null;
try
{
if (user == null) {
con = drivermanager.getconnection(url);
}
else{
con = drivermanager.getconnection(url, user, password);
}
log("连接池" + name+"创建一个新的连接");

}
catch (sqlexception e) {
log(e, "无法创建下列url的连接: " + url);
return null;
}
return con;
}
}
}

================================
/**
* title: connectpool.java
* description: 数据库操作
* copyright: copyright (c) 2002/12/25
* company:
* author :
* remark : 加入指针回滚
* version 2.0
*/

import java.io.*;
import com.sjky.pool.*;
import java.sql.*;
import java.util.*;
import java.util.date;
import java.net.*;

public class poolman extends connectpool {

private connectpool connmgr;
private statement stmt;
private connection con ;
private resultset rst;

/**
*对象连接初始化
* */

public connection getpool(string name) throws exception
{
try{
connmgr = connectpool.getinstance();
con = connmgr.getconnection(name);
}catch(exception e)
{
system.err.println("不能创建连接!请尝试重启应用服务器");

}
return con;
}

/**
*同以上方法,加入连接空闲等待时间
*待用方法
* */

public connection getpool_t(string name, long time) throws exception
{
try{
connmgr = connectpool.getinstance();
con = connmgr.getconnection(name,time);
}catch(exception e)
{
system.err.println("不能创建连接!");

}
return con;
}
/**
*执行查询方法1
* */
public resultset executequery(string sqlstr) throws exception
{
resultset result = null;
try
{
stmt = con.createstatement();
result = stmt.executequery(sqlstr);
// here add one line by jnma 12.11
con.commit();
}
catch(java.sql.sqlexception e)
{
throw new exception("执行查询语句出错");
}
return result;
}
/**
*执行查询方法2
* */
public resultset getrst(string sqlstr) throws exception
{
// resultset result = null;
try
{
stmt = con.createstatement(resultset.type_scroll_sensitive,resultset.concur_updatable);
rst = stmt.executequery(sqlstr);
// here add one line by jnma 12.11
con.commit();
}
catch(java.sql.sqlexception e)
{
throw new exception("执行查询语句出错");
}
return rst;
}
/**
*执行更新
* */
public int update(string sqlstr) throws exception
{
int result = -1;
try
{
stmt = con.createstatement(resultset.type_scroll_sensitive,resultset.concur_updatable);
result = stmt.executeupdate(sqlstr);
// here add one line by jnma 12.11
con.commit();
if(result==0)
system.out.println("执行delete,update,insert sql出错");
}
catch(java.sql.sqlexception e)
{
system.err.println("执行delete,update,insert sql出错");
}
return result;
}

/**
*执行事务处理
* */
public boolean handletransaction(vector sqlarray) throws exception
{
boolean result = false;
int arraysize = sqlarray.size();
try
{
stmt = con.createstatement();
con.setautocommit(false);
system.out.println("arraysize is" +arraysize);
for(int i=0;i<arraysize;i++)
{
system.out.println(" 开始执行语句"+(string)sqlarray.elementat(i));
stmt.executeupdate((string)sqlarray.elementat(i));
system.out.println(" 执行成功");
}
con.commit();
con.setautocommit(true) ;//必须
system.out.println("事务执行成功");
result = true;
}
catch(java.sql.sqlexception e)
{
try
{
system.out.println(e.tostring());
system.out.println("数据库操作失败");
con.rollback();
}
catch(java.sql.sqlexception te)
{
system.err.println("事务出错回滚异常");
}
}
try
{
con.setautocommit(true);
}
catch(java.sql.sqlexception e)
{
system.err.println("设置自动提交失败");
}
return result;
}

/**
*释放连接
* */
public void close(string name) throws exception
{
try
{
if(stmt!=null)
stmt.close();
if(con!=null)
{
connmgr.freeconnection(name,con);

system.out.println(" [c 正在释放一个连接 ] ");

}
}
catch(java.sql.sqlexception e)
{
system.err.println("释放连接出错");
}
}

}
===========================
属性文件db.properties放在conf下

#drivers=com.inet.tds.tdsdriver
#logfile=c:/resin-2.1.4/dbconnectpool-log.txt
#test.maxconn=1000
#test.url=jdbc:inetdae:server:1433?sql7=true
#test.user=sa
#test.password=test

drivers=com.microsoft.jdbc.sqlserver.sqlserverdriver
logfile=f:/resin-2.1.4/dbconnectpool-log.txt
test.maxconn=20
test.url=jdbc:microsoft:sqlserver://192.168.0.5:1433;databasename=test
test.user=sa
test.password=test

#drivers=oracle.jdbc.driver.oracledriver
#logfile=c:/resin-2.1.4/dbconnectpool-log.txt
#test.maxconn=100
#test.url=jdbc:oracle:thin:@192.168.0.10:1521:myhome
#test.user=system
#test.password=manager
#mysql端3306

#drivers=org.gjt.mm.mysql.driver
#logfile=c:/resin-2.1.4/dbconnectpool-log.txt
#test.maxconn=100
#test.url=jdbc:mysql://192.168.0.4:3306/my_test
#test.user=root
#test.password=system

扫描关注微信公众号