在spring 配置文件中写
<bean id="reportJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dynamicDataSource"/></bean>
新建一个类 继承 AbstractRoutingDataSource
@Component("dynamicDataSource")
public class DynamicDataSource extends AbstractRoutingDataSource implements DisposableBean {@Resource
private IReportFacade reportFacade;
private List<DataSource> dataSources = new ArrayList<DataSource>();
private volatile boolean init = false;
final static Map<Object, Object> daMap = new HashMap<Object, Object>();
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSource.class);
protected Object determineCurrentLookupKey() {
return DataSourceFetcher.getSourceId();
}
protected DataSource determineTargetDataSource() {
String key = DataSourceFetcher.getSourceId();
DataSource dataSource = (DataSource) daMap.get(key);
if (dataSource == null) {
ReportDataSource reportDataSource = reportFacade.getDataSourceById(key);
if (reportDataSource == null) {
throw new RuntimeException("数据源Id[" + key + "]不存在");
}
try {
dataSource = createBy(reportDataSource);
daMap.put(key, dataSource);
} catch (SQLException e) {
throw new RuntimeException("数据源Id[" + key + "]配置错误,初始化失败");
}
}
return dataSource;
}
private DataSource createBy(ReportDataSource reportDataSource) throws SQLException {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(reportDataSource.getSourceStr());
dataSource.setUsername(reportDataSource.getUserName());
dataSource.setPassword(reportDataSource.getPwd());
String dbType = JdbcUtils.getDbType(dataSource.getUrl(), null);
if (JdbcConstants.MYSQL.equals(dbType)) {
dataSource.setValidationQuery("select 1");
} else if (JdbcConstants.ORACLE.equals(dbType)) {
dataSource.setValidationQuery("select 1 from dual");
} else {
//
}
dataSource.init();
dataSources.add(dataSource);
return dataSource;
}
再调用jdbc查询时 DataSourceFetcher.setSourceId();