日期:2014-05-17 浏览次数:20996 次
public class DBProxyUtil {
	private static Connection conn = null;
	private static List<Connection> pool = new ArrayList<Connection>();
	static{
		String dirver = "com.mysql.jdbc.Driver";
		String uri = "jdbc:mysql:///user?characterEncoding=UTF8";
		String name = "root";
		String pwd = "root";
		try {
			//初始化一个含有10个连接的连接池
			for(int index = 0;index < 10;index++){
				Class.forName(dirver);
				conn = DriverManager.getConnection(uri,name,pwd);
  //代理对象
				Object obj = Proxy.newProxyInstance(DBProxyUtil.class.getClassLoader(),
						new Class[]{Connection.class},  //所需要代理类的接口类
						new InvocationHandler(){  //句柄,这里主要拦截代理类方法,除getClass方法外
							public Object invoke(Object proxy, Method method,
									Object[] args) throws Throwable {
								if("close".equals(method.getName())){
									//当进行关闭操作是,代理连接不进行关闭操作,将所用连接返回到连接池中
									System.out.println("关闭连接。。");
									synchronized (pool) {
										//将连接放回连接池
										pool.add((Connection)proxy);
										//唤醒等待的线程
										pool.notify();
									}
									return null;
								}else{
									//执行除close方法之外的方法,这里的o对象是方法返回值对象
									Object o = method.invoke(conn, args);
									return o;
								}
							}
					
				});
				pool.add((Connection)obj);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public static Connection getConn(){
		synchronized (pool) {
			//当连接池中的连接个数为0时,线程进入等待队列
			if(pool.size() == 0){
				try {
					pool.wait();
				} catch&