核心: AbstractRoutingDataSource
定义一个类继承AbstractRoutingDataSource
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceHolder.get();
}
}
配置的时候注入:
public void setTargetDataSources(Map<Object, Object> targetDataSources) {
this.targetDataSources = targetDataSources;
}
并且重写:
@Nullable
protected abstract Object determineCurrentLookupKey();
这个key就是真正和实际DataSource的映射key:
当然还有个默认的dataSource: resolvedDefaultDataSource
this.targetDataSources.forEach((key, value) -> {
Object lookupKey = resolveSpecifiedLookupKey(key);
DataSource dataSource = resolveSpecifiedDataSource(value);
this.resolvedDataSources.put(lookupKey, dataSource);
});
if (this.defaultTargetDataSource != null) {
this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource);
}
其实很简单,就这么多。
网友评论