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);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值