使用JDK动态代理完成自定义连接池

public class MyDataSource implements DataSource {

	private String username;
	private String password;
	private String url;
	private String driverClassName;
	private List list = new ArrayList(); 
	private boolean flag = true;

	private void init() throws SQLException {
		flag = false;
		try {
			Class.forName(driverClassName);
		} catch(ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
		for(int i = 0; i < 5; i++) {
			final Connection con = DriverManager.getConnection(url, username, password);
			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
			Class[] ins = {Connection.class};
			InvocationHandler inHandler = new InvocationHandler() {
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					if(method.getName().equals("close")) {
						list.add((Connection)proxy);
						return null;
					} else {
						return method.invoke(con, args);
					}
				}
			};
			Connection proxy = (Connection)Proxy.newProxyInstance(classLoader, ins, inHandler);
			list.add(proxy);
		}
	}
	
	public Connection getConnection() throws SQLException {
		if(flag) {
			init();
		}
		if(list.size() > 0) {
			return list.remove(0);
		}
		throw new RuntimeException();
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		// TODO Auto-generated method stub

	}

	@Override
	public int getLoginTimeout() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public  T unwrap(Class iface) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isWrapperFor(Class iface) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Connection getConnection(String username, String password)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

}

你可能感兴趣的:(使用JDK动态代理完成自定义连接池)