现在的位置: 首页 > 综合 > 正文

利用AbstractRoutingDataSource实现动态数据源切换

2017年12月07日 ⁄ 综合 ⁄ 共 6319字 ⁄ 字号 评论关闭

First Solution: 来自百度空间,比较详细


http://baike.baidu.com/view/4146963.htm

 

Second Solution:


在Spring 2.0.1中引入了AbstractRoutingDataSource, 该类充当了DataSource的路由中介, 能有在运行时, 根据某种key值来动态切换到真正的DataSource上。

     Spring动态配置多数据源,即在大型应用中对数据进行切分,并且采用多个数据库实例进行管理,这样可以有效提高系统的水平伸缩性。而这样的方案就会不同于常见的单一数据实例的方案,这就要程序在运行时根据当时的请求及系统状态来动态的决定将数据存储在哪个数据库实例中,以及从哪个数据库提取数据。

 
Spring对于多数据源,以数据库表为参照,大体上可以分成两大类情况: 
一是,表级上的跨数据库。即,对于不同的数据库却有相同的表(表名和表结构完全相同)。 
二是,非表级上的跨数据库。即,多个数据源不存在相同的表。 
Spring2.x的版本中采用Proxy模式,就是我们在方案中实现一个虚拟的数据源,并且用它来封装数据源选择逻辑,这样就可以有效地将数据源选择逻辑从Client中分离出来。Client提供选择所需的上下文(因为这是Client所知道的),由虚拟的DataSource根据Client提供的上下文来实现数据源的选择。 
具体的实现就是,虚拟的DataSource仅需继承AbstractRoutingDataSource实现determineCurrentLookupKey()在其中封装数据源的选择逻辑。

 

一、原理

首先看下AbstractRoutingDataSource类结构,继承了AbstractDataSource


Java代码  收藏代码
  1. <span>public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean</span>  

 

既然是AbstractDataSource,当然就是javax.sql.DataSource的子类,于是我们自然地回去看它的getConnection方法:


Java代码  收藏代码
  1. <span>public Connection getConnection() throws SQLException {  
  2.         return determineTargetDataSource().getConnection();  
  3.     }  
  4.   
  5.     public Connection getConnection(String username, String password) throws SQLException {  
  6.         return determineTargetDataSource().getConnection(username, password);  
  7.     }</span>  

 

 原来关键就在determineTargetDataSource()里:


Java代码  收藏代码
  1. <span>/** 
  2.      * Retrieve the current target DataSource. Determines the 
  3.      * {@link #determineCurrentLookupKey() current lookup key}, performs 
  4.      * a lookup in the {@link #setTargetDataSources targetDataSources} map, 
  5.      * falls back to the specified 
  6.      * {@link #setDefaultTargetDataSource default target DataSource} if necessary. 
  7.      * @see #determineCurrentLookupKey() 
  8.      */  
  9.     protected DataSource determineTargetDataSource() {  
  10.         Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");  
  11.         Object lookupKey = determineCurrentLookupKey();  
  12.         DataSource dataSource = this.resolvedDataSources.get(lookupKey);  
  13.         if (dataSource == null && (this.lenientFallback || lookupKey == null)) {  
  14.             dataSource = this.resolvedDefaultDataSource;  
  15.         }  
  16.         if (dataSource == null) {  
  17.             throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");  
  18.         }  
  19.         return dataSource;  
  20.     }</span>  

 这里用到了我们需要进行实现的抽象方法determineCurrentLookupKey(),该方法返回需要使用的DataSource的key值,然后根据这个key从resolvedDataSources这个map里取出对应的DataSource,如果找不到,则用默认的resolvedDefaultDataSource。


Java代码  收藏代码
  1. <span>public void afterPropertiesSet() {  
  2.         if (this.targetDataSources == null) {  
  3.             throw new IllegalArgumentException("Property 'targetDataSources' is required");  
  4.         }  
  5.         this.resolvedDataSources = new HashMap<Object, DataSource>(this.targetDataSources.size());  
  6.         for (Map.Entry entry : this.targetDataSources.entrySet()) {  
  7.             Object lookupKey = resolveSpecifiedLookupKey(entry.getKey());  
  8.             DataSource dataSource = resolveSpecifiedDataSource(entry.getValue());  
  9.             this.resolvedDataSources.put(lookupKey, dataSource);  
  10.         }  
  11.         if (this.defaultTargetDataSource != null) {  
  12.             this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource);  
  13.         }  
  14.     }</span>  

 

二、Spring配置多数据源的方式和具体使用过程


1、数据源的名称常量类

    public enum DynamicDataSourceGlobal {

Java代码  收藏代码
  1.     ORCL,   
  2.     ISC  
  3. }  

 

2、建立一个获得和设置上下文环境的类,主要负责改变上下文数据源的名称

    public class DynamicDataSourceHolder {

Java代码  收藏代码
  1. // 线程本地环境  
  2. private static final ThreadLocal<DynamicDataSourceGlobal> contextHolder = new ThreadLocal<DynamicDataSourceGlobal>();  
  3.   
  4. // 设置数据源类型  
  5. public static void setDataSourceType(DynamicDataSourceGlobal dataSourceType) {  
  6.     Assert.notNull(dataSourceType, "DataSourceType cannot be null");  
  7.     contextHolder.set(dataSourceType);  
  8. }  
  9.   
  10. // 获取数据源类型  
  11. public static DynamicDataSourceGlobal getDataSourceType() {  
  12.     return (DynamicDataSourceGlobal) contextHolder.get();  
  13. }  
  14.   
  15. // 清除数据源类型  
  16. public static void clearDataSourceType() {  
  17.     contextHolder.remove();  
  18. }  

 

3、建立动态数据源类,注意,这个类必须继承AbstractRoutingDataSource,且实现方法 determineCurrentLookupKey,该方法返回一个Object,一般是返回字符串

    public class DynamicDataSource extends AbstractRoutingDataSource {

Java代码  收藏代码
  1.     @Override  
  2.     protected Object determineCurrentLookupKey() {  
  3.         return DynamicDataSourceHolder.getDataSourceType();  
  4.     }  
  5.   
  6. }  

4、编写spring的配置文件配置多个数据源

     <!-- 数据源相同的内容 -->

Java代码  收藏代码
  1.     <bean id="parentDataSource"  
  2.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  3.         <property name="driverClass"  
  4.             value="oracle.jdbc.pool.OracleConnectionPoolDataSource" />  
  5.         <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />  
  6.         <property name="user" value="isc_v10" />  
  7.         <property name="password" value="isc" />  
  8.     </bean>  
  9.   
  10.     <!-- 数据源 -->  
  11.     <bean id="orclDataSource" parent="parentDataSource">  
  12.         <property name="user" value="orcl" />  
  13.         <property name="password" value="orcl" />  
  14.     </bean>  
  15.   
  16.     <!-- 数据源 -->  
  17.     <bean id="iscDataSource" parent="parentDataSource">  
  18.         <property name="user" value="isc_v10" />  
  19.         <property name="password" value="isc" />  
  20.     </bean>  
  21.   
  22.     <!-- 编写spring 配置文件的配置多数源映射关系 -->  
  23.     <bean id="dataSource" class="com.wy.config.DynamicDataSource">  
  24.         <property name="targetDataSources">  
  25.             <map key-type="java.lang.String">  
  26.                 <entry key="ORCL" value-ref="orclDataSource"></entry>  
  27.                 <entry key="ISC" value-ref="iscDataSource"></entry>  
  28.             </map>  
  29.         </property>  
  30.         <property name="defaultTargetDataSource" ref="orclDataSource">  
  31.         </property>  
  32.     </bean>  
  33.   
  34.     <bean id="sessionFactory"  
  35.         class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">  
  36.         <property name="dataSource" ref="dataSource" />  
  37. </bean>  

 

5、使用

   @Test

Java代码  收藏代码
  1. public void testSave() {  
  2.     // hibernate创建实体  
  3.     DynamicDataSourceHolder.setDataSourceType(DynamicDataSourceGlobal.ORCL);// 设置为另一个数据源  
  4.     com.wy.domain.Test user = new com.wy.domain.Test();  
  5.   
  6.     user.setName("WY");  
  7.     user.setAddress("BJ");  
  8.   
  9.     testDao.save(user);// 使用dao保存实体  
  10.   
  11.     DynamicDataSourceHolder.setDataSourceType(DynamicDataSourceGlobal.ISC);// 设置为另一个数据源  
  12.   
  13.     testDao.save(user);// 使用dao保存实体到另一个库中  
  14.   
  15. }  

抱歉!评论已关闭.