日期:2014-05-16  浏览次数:20548 次

nutz中实现多数据库切换
nutz很好的实现了表切换
根据它的思路写了个数据库切换,测试可行!
public class MutiDataSource implements DataSource {

	private static ConcurrentHashMap<String, DruidDataSource> dataSourceMap = new ConcurrentHashMap<String, DruidDataSource>();

	protected HashMap<String, String> dsdbMap;
	protected String driverClassName;
	protected String url;
	protected String username;
	protected String password;
	protected int maxActive;

	public MutiDataSource() {

	}

	public void init() throws SQLException {
		Iterator<String> it = dsdbMap.keySet().iterator();
		String dsname, dbname;
		while (it.hasNext()) {
			dsname = it.next();
			dbname = dsdbMap.get(dsname);
			DruidDataSource ds = createDataSource(dbname);
			dataSourceMap.put(dsname, ds);
		}
	}

	public void close() {
		Iterator<DruidDataSource> it = dataSourceMap.values().iterator();
		while (it.hasNext()) {
			it.next().close();
		}
	}

	protected DruidDataSource createDataSource(String dbname) {
		DruidDataSource ds = new DruidDataSource();
		ds.setDriverClassName(driverClassName);
		ds.setUsername(username);
		ds.setPassword(password);
		ds.setUrl(url + dbname);
		return ds;
	}

	public DataSource getDs() {
		return dataSourceMap.get(DataSourceNames.get());
	}

	public void setDriverClassName(String driverClassName) {
		this.driverClassName = driverClassName;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setMaxActive(int maxActive) {
		this.maxActive = maxActive;
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return getDs().getLogWriter();
	}

	@Override
	public int getLoginTimeout() throws SQLException {
		return getDs().getLoginTimeout();
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		getDs().setLogWriter(out);
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		getDs().setLoginTimeout(seconds);
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return getDs().isWrapperFor(iface);
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return getDs().unwrap(iface);
	}

	@Override
	public Connection getConnection() throws SQLException {
		return getDs().getConnection();
	}

	@Override
	public Connection getConnection(String username, String password)
			throws SQLException {
		return getDs().getConnection(username, password);
	}

}


public class DataSourceNames {
	private static final ThreadLocal<String> ds = new ThreadLocal<String>();

	public static String get() {
		return ds.get();
	}

	public static String set(String obj) {
		String re = get();
		ds.set(obj);
		return re;
	}

	public static void clear() {
		set(null);
	}

}