动态代理练习3-自定义数据库连接池[connection动态代理]
2013-05-01 19:48
323 查看
自定义数据库连接池[connection动态代理]
1、代理类
2、测试类
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()); } }
相关文章推荐
- 动态代理练习3-自定义数据库连接池[connection动态代理]
- 【Java EE 学习 15】【自定义数据库连接池之动态代理的使用】
- 动态代理实现数据库连接池功能(代理Connection的close方法)
- 关于利用动态代理手写数据库连接池的异常 java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to java.sql.Connection
- 使用JAVA中的动态代理实现数据库连接池
- 动态代理练习2-全站压缩流输出[response动态代理]
- 使用 JAVA 中的动态代理实现数据库连接池
- 自己用JDK动态代理写一个基本数据库连接池
- 使用 JAVA 中的动态代理实现数据库连接池
- 使用JAVA中的动态代理实现数据库连接池
- 使用JAVA中的动态代理实现数据库连接池
- 使用 JAVA 中的动态代理实现数据库连接池
- 使用JAVA中的动态代理实现数据库连接池
- 动态代理模式--自定义数据源的终极…
- 【iOS开发-62】自定义cell制作团购页面、顶部图片轮播、底部模拟加载更多功能,核心是练习代理模式
- 使用JDK动态代理完成自定义连接池
- 使用JAVA中的动态代理实现数据库连接池
- 使用JAVA中的动态代理实现数据库连接池
- (转)使用JAVA中的动态代理实现数据库连接池
- 通过JDK动态代理和自定义注解来控制方法级别的权限访问