您的位置:首页 > 数据库

动态代理练习3-自定义数据库连接池[connection动态代理]

2013-05-01 19:48 323 查看
自定义数据库连接池[connection动态代理]

  



1、代理类

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

//    自定义连接池
public class Pool {

private static LinkedList<Connection> linkedList = new LinkedList<Connection>();
static{
//        在加载Pool类时,创建10个连接,并加入到连接池中
for (int i = 0; i < 10; i++) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/bbs";
String user = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, user, password);
//                将连接添加到末尾
linkedList.addLast(conn);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//    取得连接池中连接的个数
public int getSize(){
return linkedList.size();
}
//    取得一个空闲的连接,只能返回Connection的动态代理对象
public Connection getConnection(){
final Connection conn =linkedList.removeFirst();
Class<?>[] interfaces =conn.getClass().getInterfaces();
for(Class<?> clazz:interfaces){
System.out.println(clazz.getName());
}
return (Connection) Proxy.newProxyInstance(
Pool.class.getClassLoader(),
new Class[]{Connection.class},
new InvocationHandler() {

public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {

//                        如果调用的是close()方法
if("close".equals(method.getName())){
//                            将连接放回连接池
linkedList.addLast(conn);
//                            放回null
return null;
}else{
return method.invoke(conn, args);
}
}
});
}

//    返回真实的Connection
/*public Connection getConnection(){
Connection conn = linkedList.removeFirst();
return conn;//返回真实的Connection
}*/

}


2、测试类

import java.sql.Connection;
import java.sql.SQLException;

public class TestPool {

public static void main(String[] args) throws SQLException {

//        创建连接池
Pool pool = new Pool();
//        取得连接池中的连接个数
System.out.println("连接个数为:"+pool.getSize());
//        取得一个空闲的连接
Connection conn = pool.getConnection();
//        取得连接池中的连接个数
System.out.println("连接个数为:"+pool.getSize());
//        关闭连接对象,本质是将连接放回连接池
conn.close();
System.out.println("连接个数为:"+pool.getSize());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: