超级简单的数据库连接池

文章作者 100test 发表时间 2007:03:14 16:30:52
来源 100Test.Com百考试题网


连接池最基本的目的:
1、重用连接,节省连接资源;
2、免去建立连接操作,提高效率
3. 限制最大连接并发数


自己弄的一个连接池,绝对高效安全,支持多数据源


连接池的两种实现方式:

1. 修饰模式弄个ConnectionWrapper类出来
2. 动态代理


这里采用的是第一种方式



ConnectionAdapter implements Connetion
ConnectionWrapper extends ConnectionAdapter

ConnectionWrapper 中封装了connection对象
close方法重写为
{
SimpleConnectionPool.putConnectionToPool(this).
//把连接返回连接池
}


配置文件 app.properties


ConnectionAdapter 从DBCP拷贝过来,删了些垃圾东西

支持多数据源

DBUtil.getConn().//获取默认连接池
DBUtil.getConn(pool_name).//获取指定名称的连接池



各参数说明

pool_name.dirver

driver=net.sourceforge.jtds.jdbc.Driver
url=jdbc:jtds:sqlserver://127.0.0.1:1433/data
user=sa
pwd=sa
type=sqlserver //数据库类型
pool=1 //是否使用连接池 1 使用
max_wait=3 //连接池已满时,最大等待时间 ,单位 s
#timeout ,wait time when max active , unit s
max_active=20 //最大活动连接数,用这个来控制最大并发数
min_free=3 //连接池中最小空闲连接数
max_free=20 //连接池中最大空闲连接数,默认=max_active
check_sql=0select getdate() //验证连接是否有效,
clear_time=2 //清理空闲连接
#clear_time,remove the old connection,unit min




还可以用动态代理的方式实现连接池


2.

动态代理实现



class ConnectionWrapper implements InvocationHandler {

private final static String CLOSE_METHOD_NAME = "close".
public Connection connection = null.
private Connection m_originConnection = null.

ConnectionWrapper(Connection con,String pool_name)throws Exception {
this.pool_name=pool_name.

this.check_sql = getCheckSqlByPoolName(pool_name).

last_use_time = System.currentTimeMillis().
create = StringUtil.getNowTime() "".

Class[] interfaces = {java.sql.Connection.class}.
this.connection = (Connection) Proxy.newProxyInstance(
con.getClass().getClassLoader(),
interfaces, this).
m_originConnection = con.
}


void close() {
//m_originConnection.close().
DBUtil.close(m_originConnection).
}

public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object obj = null.
if (CLOSE_METHOD_NAME.equals(m.getName())) {
//SimpleConnectionPool.pushConnectionBackToPool(this).
SimpleConnectionPool.putConnectionToPool(this).

}
else {

obj = m.invoke(m_originConnection, args).
//last_use_time = System.currentTimeMillis().
}


return obj.
}


}


相关文章


Java网络编程之URI、URL研究专题四(2)
Java网络编程之URI、URL研究专题三(2)
超级简单的数据库连接池
JAVA高级编程:Java中的多线程
Java语言深入文件和流(4)
澳大利亚华人论坛
考好网
日本华人论坛
华人移民留学论坛
英国华人论坛