Java数据库编程
时间:2021-07-01 10:21:17
帮助过:2人阅读
class DBConnectionPool
{
private String jdbcUrl;
private String username;
private String password;
private LinkedList<Connection>
pool; //保存闲置的Connection对象
public DBConnectionPool(String driver,String jdbcUrl)
throws ClassNotFoundException
{
this.jdbcUrl =
jdbcUrl;
Class.forName(driver);
pool =
new LinkedList<Connection>
();
}
public DBConnectionPool(String driver,String jdbcUrl,String username,String password)
throws ClassNotFoundException
{
this.jdbcUrl =
jdbcUrl;
this.username =
username;
this.password =
password;
Class.forName(driver);
pool =
new LinkedList<Connection>
();
}
//为了可以在多线程环境下使用,对一些方法使用synchronized关键字同步
public synchronized Connection getConnection()
throws SQLException
{
Connection conn =
null;
if(pool.size() > 0
)
conn =
pool.poll();
else
{
final Connection connection =
DriverManager.getConnection(jdbcUrl, username, password);
//创建代理对象,并强制转换为Connection接口类型,InvocationHandler接口表示调用处理器
conn = (Connection)Proxy.newProxyInstance(
null,
new Class[]{Connection.
class},
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
if(method.getName() == "close" && method.getParameterTypes().length == 0
)
{
pool.add((Connection)proxy); //执行close方法时,替换原方法的逻辑
return null;
}
else //执行其他方法时,保持原方法的逻辑
return method.invoke(connection,args);
}
});
}
return conn;
}
public synchronized Connection getConnection(String username, String password)
throws SQLException
{
Connection conn =
null;
if(pool.size() > 0
)
conn =
pool.poll();
else
{
final Connection connection =
DriverManager.getConnection(jdbcUrl, username, password);
conn = (Connection)Proxy.newProxyInstance(
null,
new Class[]{Connection.
class},
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
if(method.getName() == "close" && method.getParameterTypes().length == 0
)
{
pool.add((Connection)proxy);
return null;
}
else
return method.invoke(connection,args);
}
});
}
return conn;
}
public synchronized void reduce()
throws SQLException
{
int size =
pool.size();
while(pool.size() > (size / 2
) )
pool.poll().close();
}
public synchronized void close()
throws SQLException
{
while(pool.size() > 0
)
pool.poll().close();
}
}
Java数据库编程
标签: