1、首先配置兩個數據庫
<bean id="dataSourceA" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxWait" value="${jdbc.maxWait}" /> </bean> <bean id="dataSourceB" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${vjdbc.driverClassName}" /> <property name="url" value="${vjdbc.url}" /> <property name="username" value="${vjdbc.username}" /> <property name="password" value="${vjdbc.password}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxWait" value="${jdbc.maxWait}" /> </bean>2、再配置一個dataSource 管理 key 值和value值對應,默認選擇dataSourceA ,其他配置按照正常的spring mvc 配置即可。
<bean id="dataSource" class="com.broadengate.util.DynamicDataSource"> <!-- 通過key-value的形式來關聯數據源 --> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry value-ref="dataSourceA" key="dataSourceA"></entry> <entry value-ref="dataSourceB" key="dataSourceB"></entry> </map> </property> <property name="defaultTargetDataSource" ref="dataSourceA" > </property> </bean>
3、sessionFactory 中使用 dataSource做數據源。
4、新建一個DynamicDataSource類繼承AbstractRoutingDataSource。
public class DynamicDataSource extends AbstractRoutingDataSource{ public static final String DATA_SOURCE_A = "dataSourceA"; public static final String DATA_SOURCE_B = "dataSourceB"; private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static void setCustomerType(String customerType) { contextHolder.set(customerType); } public static String getCustomerType() { return contextHolder.get(); } public static void clearCustomerType() { contextHolder.remove(); } @Override protected Object determineCurrentLookupKey() { return getCustomerType(); } }
5、切換數據源,這一步必須在進入業務層之前切換。
DynamicDataSource.setCustomerType(DynamicDataSource.DATA_SOURCE_A); |