Spring-dao.xml
<bean id="clickDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
<property name="maxPoolSize" value="10"/>
<property name="minPoolSize" value="5"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
</bean>
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver2}"/>
<property name="jdbcUrl" value="${url2}"/>
<property name="user" value="${user2}"/>
<property name="password" value="${password2}"/>
<property name="maxPoolSize" value="10"/>
<property name="minPoolSize" value="5"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
</bean>
<bean id ="dataSource" class= "com.taxi.utils.dbchange.DynamicDataSource" >
<property name ="targetDataSources">
<map key-type ="java.lang.String">
<entry value-ref="clickDataSource" key="clickDataSource"/>
<entry value-ref="myDataSource" key="myDataSource"/>
</map >
</property>
<property name ="defaultTargetDataSource" ref= "clickDataSource"/>
</bean>
DataSourceContextHolder
package com.taxi.utils.dbchange;
public class DataSourceContextHolder {
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
public static void setDbType(String dbType) {
CONTEXT_HOLDER.set(dbType);
}
public static String getDbType() {
return CONTEXT_HOLDER.get();
}
public static void clearDbType() {
CONTEXT_HOLDER.remove();
}
}
DataSourceType
package com.taxi.utils.dbchange;
public class DataSourceType {
public static final String SOURCE_CLICK_HOUSE = "clickDataSource";
public static final String SOURCE_MYSQL = "myDataSource";
}
DynamicDataSource
package com.taxi.utils.dbchange;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDbType();
}
}