public class DynamicDataSource extends AbstractRoutingDataSource {
public DynamicDataSource() {
}
protected Object determineCurrentLookupKey() {
String key = DynamicDataSourceHolder.getDataSouce();
System.out.println("------dataSource:" + key);
return key;
}
}
public class DynamicDataSourceHolder {
public static final ThreadLocal<String> holder = new ThreadLocal();
public DynamicDataSourceHolder() {
}
public static void putDataSource(String name) {
holder.set(name);
}
public static String getDataSouce() {
return (String)holder.get();
}
}
<bean id="shardDataSource" class="com.base.dataSource.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="master1" value-ref="dataSource1"/>
<entry key="master2" value-ref="dataSource2"/>
</map>
</property>
</bean>
<bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource" parent="dataSourceParent">
<property name="driverClassName" value="${jdbc1.driver}"/>
<property name="url" value="${jdbc1.url}"/>
<property name="username" value="${jdbc1.username}"/>
<property name="password" value="${jdbc1.password}"/>
</bean>
<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource" parent="dataSourceParent">
<property name="driverClassName" value="${jdbc2.driver}"/>
<property name="url" value="${jdbc2.url}"/>
<property name="username" value="${jdbc2.username}"/>
<property name="password" value="${jdbc2.password}"/>
</bean>
<bean id="dataSourceParent" class="org.apache.commons.dbcp.BasicDataSource">
<property name="initialSize" value="${dbcp.initialSize}"/>
<property name="maxActive" value="${dbcp.maxActive}"/>
<property name="maxIdle" value="${dbcp.maxIdle}"/>
<property name="minIdle" value="${dbcp.minIdle}"/>
<property name="maxWait" value="${dbcp.maxWait}"/>
<property name="defaultAutoCommit" value="${dbcp.defaultAutoCommit}"/>
<property name="timeBetweenEvictionRunsMillis" value="${dbcp.timeBetweenEvictionRunsMillis}"/>
<property name="numTestsPerEvictionRun" value="${dbcp.numTestsPerEvictionRun}"/>
<property name="minEvictableIdleTimeMillis" value="${dbcp.minEvictableIdleTimeMillis}"/>
<property name="testWhileIdle" value="${dbcp.testWhileIdle}"/>
<property name="testOnBorrow" value="${dbcp.testOnBorrow}"/>
<property name="testOnReturn" value="${dbcp.testOnReturn}"/>
<property name="validationQuery" value="${dbcp.validationQuery}"/>
<property name="removeAbandoned" value="${dbcp.removeAbandoned}"/>
<property name="removeAbandonedTimeout" value="${dbcp.removeAbandonedTimeout}"/>
<property name="logAbandoned" value="${dbcp.logAbandoned}"/>
</bean>