/**
* 采用动态代理技术,实现标准的连接池
* @author zhurudong
*
*/
public class DBCPool implements DataSource{
// 声明List,管理连接池
private LinkedList<Connection> pool = new LinkedList<Connection>();
// 构造函数,初始化连接池
public DBCPool() {
String driverClassName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/oa";
String username = "root";
String password = "root";
try {
Class.forName(driverClassName);
for(int i = 0; i < 3; i++){
final Connection conn = DriverManager.getConnection(url, username, password);
Object proxyedConn = Proxy.newProxyInstance(
Connection.class.getClassLoader(),
Connection.class.getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxyConn, Method method, Object[] args)
throws Throwable {
// 判断如果是close方法,不用关闭。放回到List中
if("close".equals(method.getName())){
synchronized (pool) {
pool.addLast((Connection) proxyConn);
// 因为有可能在添加到List中时,有线程正在等待获取,所以需要唤醒线程池中的某一个线程
pool.notify();
}
return null;
}
// 如果不是close方法,则传递目标对象和方法上的参数,并执行方法
Object retVal = method.invoke(conn, args);
return retVal;
}
});
pool.add((Connection) proxyedConn);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException {
synchronized (pool) {
if (pool.size() == 0) {
try {
pool.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return getConnection();
}
return pool.removeFirst();
}
}
采用动态代理技术,实现标准的连接池
最新推荐文章于 2023-10-31 17:40:49 发布