package 动态连接数据库;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.util.LinkedList;public class UtilsDB { public static void main(String[] args) { UtilsDB u = new UtilsDB(); System.err.println(u.getCon()); } private static LinkedList pool = new LinkedList (); static { try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql:///abc"; for (int i = 0; i < 3; i++) { // 真实对象 final Connection con = DriverManager.getConnection(url, "root", "1234"); // 声明代理 Object obj = Proxy.newProxyInstance( UtilsDB.class.getClassLoader(), new Class[] { Connection.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("close")) { System.err.println("有人还连接"); synchronized (pool) { pool.addLast((Connection) proxy); pool.notifyAll(); return null; } } else { return method.invoke(con, args); } } }); // 将代理人添加到pool pool.add((Connection) obj); } } catch (Exception e) { throw new RuntimeException(e); } } public static Connection getCon() { synchronized (pool) { if (pool.size() == 0) { try { pool.wait(); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return getCon(); } else { Connection con = pool.removeFirst(); System.err.println("pool.size:" + pool.size()); return con; } } }}
package 动态连接数据库;import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;public class TestDb { public static void main(String[] args) { //Connection con=UtilsDB.getCon(); //System.err.println(con); for (int i = 0; i < 110; i++) { new Thread() { public void run() { Connection con = UtilsDB.getCon(); try { Statement st = con.createStatement(); System.err.println(con + "\t" + this.getName() + "\t" + st); } catch (SQLException e) { e.printStackTrace(); } finally { try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; }.start(); } }}