java数据库缓冲池的好处和基本原理(转载)
package connectionpool;import java.lang.reflect.Proxy;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.Stack;import test.TestInterface;public class ConnectionPool { Stack<Connection> st = new Stack<Connection>(); //创建一个堆栈,作为池子 private static ConnectionPool instance = new ConnectionPool(); //单例模式 public static int initialPoolSize = 5; public static String dbName = "test"; public static String userName = "root"; public static String userPasswd = ""; private ConnectionPool() { for(int i = 0; i < initialPoolSize; i++) //初始化缓冲池 try { createConnection().close(); } catch (Exception e) { e.printStackTrace(); } } public synchronized static Connection getConnection() throws Exception { if (instance.st.size() > 0) return instance.st.pop(); else return createConnection(); } synchronized static void returnConnection(Connection conn) { instance.st.push(conn); } private static Connection createConnection() throws Exception { //以mysql为例 创建数据库连接 String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd; Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection connection=DriverManager.getConnection(url); ConnectionProxy handler = new ConnectionProxy(connection); Connection proxy = (Connection ) Proxy.newProxyInstance( //创建代理 connection.getClass().getClassLoader(), connection.getClass().getInterfaces(),handler); return proxy; }}接着实现代理类package connectionpool;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.sql.Connection;public class ConnectionProxy implements InvocationHandler{ Connection delegate; ConnectionProxy(Connection delegate) { this.delegate = delegate; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if ("close".equals(method.getName())) { //在close函数处设置钩子 ConnectionPool.returnConnection((Connection) proxy); //将数据库连接归还缓冲池,跳过了原来的close()函数 // 这里的proxy实际上就是Connection的一个代理实例 } else return method.invoke(delegate, args); } catch (Exception e){ } return null; }}使用缓冲池很简单 ConnectionPool.getConnection();使用完connection后,直接执行close()函数就行了,connection将返回缓冲池中而不是真正的关闭当然这只是实现了很简单的一个缓冲池,实用化还需要加上其他一些功能比如关闭idle连接等等接下来介绍一个实用的java数据库缓冲池 c3p0。