Skip to content

数据库多数据源

wave edited this page Aug 28, 2017 · 12 revisions

Spring的多数据源支持---AbstractRoutingDataSource,AbstractRoutingDataSource定义了抽象的determineCurrentLookupKey方法,子类实现此方法,来确定要使用的数据源

public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
	 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;
	}

        // 确定当前要使用的数据源
        protected abstract Object determineCurrentLookupKey();
}

Druid 实现多数据源支持,核心是Overwrite AbstractRoutingDataSource 的 determineCurrentLookupKey 方法

  public class MultipleDataSource extends AbstractRoutingDataSource {
	public static final String DATA_SOURCE_A = "dataSourceTestA";  // A库
	public static final String DATA_SOURCE_B = "dataSourceTestB";  // B库

	private static final ThreadLocal<String> dataSourceKey = new ThreadLocal<String>();

	public static void setDataSourceKey(String dataSource) {
		dataSourceKey.set(dataSource);
	}

	@Override
	protected Object determineCurrentLookupKey() {
		return dataSourceKey.get();
	}

	public static void clear(){
		dataSourceKey.remove();
	}
}
Clone this wiki locally