明确一点:数据库连接是一个重量级的对象,每一个连接的建立是一个复杂且很消耗资源的事情。为了复用已经创建好的连接,出现了池技术。连接池、线程池、对象池等等。这里采用动态代理实现一个简单的数据库连接池。
代码
|
|
原理
DataSource接口是必须要实现的,上面那些未实现的方法这里不做说明,都是DataSource接口中需要实现的方法。JdbcPool在加载进内存时候,就已经找数据库获取了10个数据库连接。getConnection()获取数据库连接,返回的就是Connection的一个代理对象出去。最终要做的事情是,拦截对close()方法的处理,当发现调用的是close()方法时,并不去执行释放连接,而是把连接返回到了LinkedList集合里面去了。