原文地址:http://x125858805.iteye.com/blog/2061713
一、配置文件
<span style="color: #ff9900;"><!-- 數據源配置 --> </span>
<bean id="ds1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
<property name="username" value="test" />
<property name="password" value="test" />
<property name="defaultAutoCommit" value="false"></property>
</bean>
<bean id="ds2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
<property name="username" value="test" />
<property name="password" value="test" />
<property name="defaultAutoCommit" value="false"></property>
</bean>
<bean id="dataSource" class="app.platform.mybatis.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry value-ref="ds1" key="ds1"></entry>
<entry value-ref="ds2" key="ds2"></entry>
</map>
</property>
<!-- 默認使用ds1的數據源 -->
<property name="defaultTargetDataSource" ref="ds1"></property>
</bean>
<!-- mybatis配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/mybatis/mybatis-config.xml" />
<property name="mapperLocations" value="classpath*:app/mapper/**/*.xml"/>
</bean>
<!-- 事務管理器配置,單數據源事務 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 事務攔截的類及方法 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="query*" read-only="true" />
<tx:method name="is*" read-only="true" />
<tx:method name="do*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
</tx:attributes>
</tx:advice>
<aop:config proxy-target-class="true">
<aop:advisor pointcut="execution(* app..service..*.*(..))" advice-ref="txAdvice" />
</aop:config>
重點是上面的數據源配置。
二、下面的類是在數據源中用到的
注:將下面類讓照路徑加入到項目中
package app.platform.mybatis;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDbType();
}
}
package app.platform.mybatis;
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setDbType(String dbType) {
contextHolder.set(dbType);
}
public static String getDbType() {
return ((String) contextHolder.get());
}
public static void clearDbType() {
contextHolder.remove();
}
}
這樣準備工作就做好了,下面是一個單元測試的例子。
三、測試
public class Test{
@Autowired
private TestService testService;
@Test
public void addTest() throws Exception {
User user = new User();
user.setUsername("admin");
user.setPassword("123456");
//注意這裏在調用service前切換到ds2的數據源
DataSourceContextHolder.setDbType("ds2");
testService.add(user);
}
}
四、總結
最主要的變化是DynamicDataSource 類,這個類繼承了AbstractRoutingDataSource,我們再繼續考察,發現這個類實現了datasource這個接口。
再仔細研究,發現我配置了多個數據源給DynamicDataSource,默認的數據源是ds1。
我們研究下AbstractRoutingDataSource類的代碼,主要是兩個實現datasource的方法
public Connection getConnection() throws SQLException {
return determineTargetDataSource().getConnection();
}
public Connection getConnection(String username, String password) throws SQLException {
return determineTargetDataSource().getConnection(username, password);
}
根據這段代碼發現主要玄機都在determineTargetDataSource()方法上。
Java代碼 收藏代碼
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;
}
根據這段代碼發現,首先在使用數據源之前,首先判斷使用數據源的key,也就是我們配置給
private Map<Object, Object> targetDataSources;
這個map中的key值,找到key值之後再找到對應的datasource然後並使用這個數據源。
從上面我們發現,實際上DynamicDataSource只是在內部封裝了數據源,然後調用它,只不過在內部他加了一些控制而已。(此處不知道是否可以理解爲代理模式)
再深一步想想,此處使用的orm層是mybatis,如果換成hibernate呢,或者jdbctemplate呢。
實際上這個方法都適用。