項目中我們經常會遇到多數據源的問題,尤其是數據同步或定時任務等項目更是如此。多數據源讓人最頭痛的,不是配置多個數據源,而是如何能靈活動態的切換數據源。例如在一個spring和hibernate的框架的項目中,我們在spring配置中往往是配置一個dataSource來連接數據庫,然後綁定給sessionFactory,在dao層代碼中再指定sessionFactory來進行數據庫操作。
正如上圖所示,每一塊都是指定綁死的,如果是多個數據源,也只能是下圖中那種方式。
可看出在Dao層代碼中寫死了兩個SessionFactory,這樣日後如果再多一個數據源,還要改代碼添加一個SessionFactory,顯然這並不符合開閉原則。
那麼正確的做法應該是
1. applicationContext.xml如下
<span style="font-size:12px;"><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:annotation-config />
<!-- 隱式地向 Spring 容器註冊
AutowiredAnnotationBeanPostProcessor、
CommonAnnotationBeanPostProcessor、
PersistenceAnnotationBeanPostProcessor、
RequiredAnnotationBeanPostProcessor -->
<context:component-scan base-package="com.saleSystem,com.interfaces" /><!-- 掃描包中的所有Bean,配置掃描包路徑選項 -->
<tx:annotation-driven transaction-manager="txManager" /><!--@Transactional這個註解進行的驅動,這是基於註解的方式使用事務配置聲明 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:app/jdbc.properties</value>
</property>
</bean>
<bean id="parentDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="5" />
<property name="maxActive" value="50" />
<property name="maxIdle" value="50" />
<property name="minIdle" value="0" />
<property name="maxWait" value="6000" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="25200000" />
</bean>
<bean id="adminDataSource" parent="parentDataSource">
<property name="url" value="${jdbc.url}" />
</bean>
<bean id="logDataSource" parent="parentDataSource">
<property name="url" value="${log.url}" />
</bean>
<bean id="dataSource" class="com.datasource.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="logDataSource" value-ref="logDataSource"/>
</map>
</property>
<property name="defaultTargetDataSource" ref="adminDataSource"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- hibernate 方言 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="javax.persistence.validation.mode">none</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
</props>
</property>
<property name="mappingDirectoryLocations">
<list>
<value>
classpath:hibernate
</value>
</list>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 面向切面控制權限 -->
<aop:config>
<aop:pointcut expression="execution(public * com.saleSystem.services..*.* (..))"
id="bussinessService" />
<aop:advisor pointcut-ref="bussinessService" advice-ref="txAdvice" />
</aop:config>
<!-- 諫言 -->
<!-- 事務 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true" /><!--以get開頭的方法只能從數據庫中讀取數據 -->
<tx:method name="find*" read-only="true" />
<tx:method name="query*" read-only="true"/>
<tx:method name="load*" propagation="SUPPORTS" />
<tx:method name="search*" propagation="SUPPORTS" />
<tx:method name="datagrid*" propagation="SUPPORTS" />
<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/><!--以add開頭的方法能對數據庫進行查詢、新增、刪除、編輯1 -->
<tx:method name="edit*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="save*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="remove*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="modify*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="repair" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="deleteAndRepair" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="put*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="restart*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="stop*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="change*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="check*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="start*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="porkDiv" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="send*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="porkRej" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="porkPdtRej" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="loginTimeAdd" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="productSaleBySaleIdAndType" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="sale*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
</beans></span>
2. DynamicDataSource.java
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
protected Object determineCurrentLookupKey() {
return CustomerContextHolder.getCustomerType();
}
}
3.CustomerContextHolder.java
public class CustomerContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal();
public static void setCustomerType(String customerType) {
contextHolder.set(customerType);
}
public static String getCustomerType() {
return (String) contextHolder.get();
}
public static void clearCustomerType() {
contextHolder.remove();
}
}
在《Hibernate 與 Spring 多數據源的配置》中提到
CustomerContextHolder.setCustomerType(DataSourceMap.Admin);//設置數據源
但是實際運用中,無需再選擇數據源,Spring會自動根據不同的Model找到相應的數據源。
另外AbstractRoutingDataSource類也可以實現主從表讀寫分離,目前還未嘗試,但是通過AOP+Annotation即可。
參考:1. 《spring多數據源配置》
2. 《Hibernate 與 Spring 多數據源的配置》