读书人

数据连接池的根本实现

发布时间: 2012-12-30 10:43:15 作者: rapoo

数据连接池的基本实现 .

1、 实现途径:编写JdbcPool implements java.sql.DataSource类l 静态初始化块l getConnection()l release()总结:可以解决连接池的实现问题,但是必须要求编程人员熟悉JdbcPool的使用解决此问题的方法——增强Connection的功能2、 方案列表:1) 编写Connection的子类,此方法理论上可以解决,但是没有可操作性,因为基本无法实现对Connection对象的初始化工作2) 采用装饰模式装饰模式解决方案用包装设计模式对connnction的close方法进行增强1.写一个类实现与被增强对象相同的接口2.在类中定义一个变量记住被增强对象3.在类中定义一个构造函数,接收被增强对象4.覆盖想增强的方法5.对于不想增强的方法,直接调用目标对象(被增强对象)的方法总结:装饰模式可以很好的解决问题,但是在此任然不合适,因为Connection接口中定义了太多的方法,逐个去实现非常繁琐。3) 动态代理技术实现public Connection getConnection() throws SQLException {if(list.size()>0){final Connection conn = list.removeFirst();  //mysqlSystem.out.println("用户从池中拿走了:" +  conn);System.out.println("池的大小为" + list.size());//myconnection   preparedstatement  commit closereturn (Connection)Proxy.newProxyInstance(JdbcPool.class.getClassLoader(), conn.getClass().getInterfaces(), new InvocationHandler(){public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {if(!method.getName().equalsIgnoreCase("close")){return method.invoke(conn, args);}System.out.println(conn + "被还到池中了");list.add(conn);System.out.println("池的大小为" + list.size());return null;}});/* MyConnection myconn = new MyConnection(conn,list);return myconn;    //   conn = pool.getConnection();  conn.preparedstatment  conn*/ }else{throw new RuntimeException("对不起,数据库忙,请等会再来!!");}} 

读书人网 >编程

热点推荐