首先看一下的类结构
public abstract class AbstractRoutingDataSource extends AbstractDataSource {
@Nullable
private Map<Object, Object> targetDataSources;
@Nullable
private Map<Object, Object> targetDataSources;
@Override
public Connection getConnection() throws SQLException {
return determineTargetDataSource().getConnection();
}
public Connection getConnection() throws SQLException {
return determineTargetDataSource().getConnection();
}
protected DataSource determineTargetDataSource() {
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = determineCurrentLookupKey();
DataSource dataSource = this.resolvedDataSources.get(lookupKey);
if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
dataSource = this.resolvedDefaultDataSource;
}
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
}
return dataSource;
}
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = determineCurrentLookupKey();
DataSource dataSource = this.resolvedDataSources.get(lookupKey);
if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
dataSource = this.resolvedDefaultDataSource;
}
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
}
return dataSource;
}
protected abstract Object determineCurrentLookupKey();
}
AbstractRoutingDataSource继承了AbstractDataSource,而AbstractDataSource实现了DataSource.
AbstractRoutingDataSource实现了DataSource的getConnection方法,其中调用determineTargetDataSource
获取真正的DataSource.
关键是determineCurrentLookupKey,获取key,用来从targetDataSources这个map拿到对应的DataSource.
使用方式
定义一个类,继承AbstractRoutingDataSource,定义targetDataSources,并实现determineCurrentLookupKey.
一般通过ThreadLocal存储key,这样就可以完成一个可路由的数据源.