Spring(AbstractRoutingDataSource)实现动态数据源切换

转自: http://blog.51cto.com/linhongyu/1615895

一、前言

    近期一项目A需实现数据同步到另一项目B数据库中,在不改变B项目的情况下,只好选择项目A中切换数据源,直接把数据写入项目B的数据库中。这种需求,在数据同步与定时任务中经常需要。

    那么问题来了,该如何解决多数据源问题呢?不光是要配置多个数据源,还得能灵活动态的切换数据源。以spring+hibernate框架项目为例(引用:http://blog.csdn.net/wangpeng047/article/details/8866239博客的图片):

    

    单个数据源绑定给sessionFactory,再在Dao层操作,若多个数据源的话,那不是就成了下图:

    

    可见,sessionFactory都写死在了Dao层,若我再添加个数据源的话,则又得添加一个sessionFactory。所以比较好的做法应该是下图:

    接下来就为大家讲解下如何用spring来整合这些数据源,同样以spring+hibernate配置为例。

二、实现原理

    1、扩展Spring的AbstractRoutingDataSource抽象类(该类充当了DataSource的路由中介, 能有在运行时, 根据某种key值来动态切换到真正的DataSource上。)

    从AbstractRoutingDataSource的源码中:

1 public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean

    我们可以看到,它继承了AbstractDataSource,而AbstractDataSource不就是javax.sql.DataSource的子类,So我们可以分析下它的getConnection方法:

1 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 }

    获取连接的方法中,重点是determineTargetDataSource()方法,看源码:

 
 1 /** 
 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     }

    上面这段源码的重点在于determineCurrentLookupKey()方法,这是AbstractRoutingDataSource类中的一个抽象方法,而它的返回值是你所要用的数据源dataSource的key值,有了这个key值,resolvedDataSource(这是个map,由配置文件中设置好后存入的)就从中取出对应的DataSource,如果找不到,就用配置默认的数据源。

    看完源码,应该有点启发了吧,没错!你要扩展AbstractRoutingDataSource类,并重写其中的determineCurrentLookupKey()方法,来实现数据源的切换:

 1 package com.datasource.test.util.database;
 2 
 3 import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
 4 
 5 /**
 6  * 获取数据源(依赖于spring)
 7  * @author linhy
 8  */
 9 public class DynamicDataSource extends AbstractRoutingDataSource{
10     @Override
11     protected Object determineCurrentLookupKey() {
12         return DataSourceHolder.getDataSource();
13     }
14 }

    DataSourceHolder这个类则是我们自己封装的对数据源进行操作的类:

 1 package com.datasource.test.util.database;
 2 
 3 /**
 4  * 数据源操作
 5  * @author linhy
 6  */
 7 public class DataSourceHolder {
 8     //线程本地环境
 9     private static final ThreadLocal<String> dataSources = new ThreadLocal<String>();
10     //设置数据源
11     public static void setDataSource(String customerType) {
12         dataSources.set(customerType);
13     }
14     //获取数据源
15     public static String getDataSource() {
16         return (String) dataSources.get();
17     }
18     //清除数据源
19     public static void clearDataSource() {
20         dataSources.remove();
21     }
22 
23 }

    2、有人就要问,那你setDataSource这方法是要在什么时候执行呢?当然是在你需要切换数据源的时候执行啦。手动在代码中调用写死吗?这是多蠢的方法,当然要让它动态咯。所以我们可以应用spring aop来设置,把配置的数据源类型都设置成为注解标签,在service层中需要切换数据源的方法上,写上注解标签,调用相应方法切换数据源咯(就跟你设置事务一样):

1 @DataSource(name=DataSource.slave1)
2 public List getProducts(){
 

    当然,注解标签的用法可能很少人用到,但它可是个好东西哦,大大的帮助了我们开发:

 1 package com.datasource.test.util.database;
 2 
 3 import java.lang.annotation.*;
 4 
 5 @Target({ElementType.METHOD, ElementType.TYPE})
 6 @Retention(RetentionPolicy.RUNTIME)
 7 @Documented
 8 public @interface DataSource {
 9     String name() default DataSource.master;
10 
11     public static String master = "dataSource1";
12 
13     public static String slave1 = "dataSource2";
14 
15     public static String slave2 = "dataSource3";
16 
17 }

三、配置文件

    为了精简篇幅,省略了无关本内容主题的配置。

    项目中单独分离出application-database.xml,关于数据源配置的文件。

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <!-- Spring 数据库相关配置 放在这里 -->
  3 <beans xmlns="http://www.springframework.org/schema/beans"
  4        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5        xmlns:aop="http://www.springframework.org/schema/aop"
  6        xmlns:tx="http://www.springframework.org/schema/tx"
  7        xsi:schemaLocation="http://www.springframework.org/schema/beans
  8        http://www.springframework.org/schema/beans/spring-beans.xsd
  9        http://www.springframework.org/schema/aop
 10         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
 11         http://www.springframework.org/schema/tx
 12         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
 13 
 14     <bean id = "dataSource1" class = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource">   
 15         <property name="url" value="${db1.url}"/>
 16         <property name = "user" value = "${db1.user}"/>
 17         <property name = "password" value = "${db1.pwd}"/>
 18         <property name="autoReconnect" value="true"/>
 19         <property name="useUnicode"  value="true"/>
 20         <property name="characterEncoding" value="UTF-8"/>
 21     </bean>
 22 
 23     <bean id = "dataSource2" class = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
 24         <property name="url" value="${db2.url}"/>
 25         <property name = "user" value = "${db2.user}"/>
 26         <property name = "password" value = "${db2.pwd}"/>
 27         <property name="autoReconnect" value="true"/>
 28         <property name="useUnicode"  value="true"/>
 29         <property name="characterEncoding" value="UTF-8"/>
 30     </bean>
 31 
 32     <bean id = "dataSource3" class = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
 33         <property name="url" value="${db3.url}"/>
 34         <property name = "user" value = "${db3.user}"/>
 35         <property name = "password" value = "${db3.pwd}"/>
 36         <property name="autoReconnect" value="true"/>
 37         <property name="useUnicode"  value="true"/>
 38         <property name="characterEncoding" value="UTF-8"/>
 39     </bean>
 40     <!-- 配置多数据源映射关系 -->
 41     <bean id="dataSource" class="com.datasource.test.util.database.DynamicDataSource">
 42         <property name="targetDataSources">
 43             <map key-type="java.lang.String">
 44         <entry key="dataSource1" value-ref="dataSource1"></entry>
 45                 <entry key="dataSource2" value-ref="dataSource2"></entry>
 46                 <entry key="dataSource3" value-ref="dataSource3"></entry>
 47             </map>
 48         </property>
 49     <!-- 默认目标数据源为你主库数据源 -->
 50         <property name="defaultTargetDataSource" ref="dataSource1"/>
 51     </bean>
 52 
 53     <bean id="sessionFactoryHibernate" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
 54         <property name="dataSource" ref="dataSource"/>
 55         <property name="hibernateProperties">
 56             <props>
 57                 <prop key="hibernate.dialect">com.datasource.test.util.database.ExtendedMySQLDialect</prop>
 58                 <prop key="hibernate.show_sql">${SHOWSQL}</prop>
 59                 <prop key="hibernate.format_sql">${SHOWSQL}</prop>
 60                 <prop key="query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
 61                 <prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop>
 62                 <prop key="hibernate.c3p0.max_size">30</prop>
 63                 <prop key="hibernate.c3p0.min_size">5</prop>
 64                 <prop key="hibernate.c3p0.timeout">120</prop>
 65                 <prop key="hibernate.c3p0.idle_test_period">120</prop>
 66                 <prop key="hibernate.c3p0.acquire_increment">2</prop>
 67                 <prop key="hibernate.c3p0.validate">true</prop>
 68                 <prop key="hibernate.c3p0.max_statements">100</prop>
 69             </props>
 70         </property>
 71     </bean>
 72 
 73     <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
 74         <property name="sessionFactory" ref="sessionFactoryHibernate"/>
 75     </bean>
 76 
 77     <bean id="dataSourceExchange" class="com.datasource.test.util.database.DataSourceExchange"/>
 78 
 79     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
 80         <property name="sessionFactory" ref="sessionFactoryHibernate"/>
 81     </bean>
 82 
 83     <tx:advice id="txAdvice" transaction-manager="transactionManager">
 84         <tx:attributes>
 85             <tx:method name="insert*" propagation="NESTED" rollback-for="Exception"/>
 86             <tx:method name="add*" propagation="NESTED" rollback-for="Exception"/>
 87             <tx:method name="update*" propagation="NESTED" rollback-for="Exception"/>
 88             <tx:method name="modify*" propagation="NESTED" rollback-for="Exception"/>
 89             <tx:method name="edit*" propagation="NESTED" rollback-for="Exception"/>
 90             <tx:method name="del*" propagation="NESTED" rollback-for="Exception"/>
 91             <tx:method name="save*" propagation="NESTED" rollback-for="Exception"/>
 92             <tx:method name="send*" propagation="NESTED" rollback-for="Exception"/>
 93             <tx:method name="get*" read-only="true"/>
 94             <tx:method name="find*" read-only="true"/>
 95             <tx:method name="query*" read-only="true"/>
 96             <tx:method name="search*" read-only="true"/>
 97             <tx:method name="select*" read-only="true"/>
 98             <tx:method name="count*" read-only="true"/>
 99         </tx:attributes>
100     </tx:advice>
101 
102     <aop:config>
103         <aop:pointcut id="service" expression="execution(* com.datasource..*.service.*.*(..))"/>
104         <!-- 关键配置,切换数据源一定要比持久层代码更先执行(事务也算持久层代码) -->
105         <aop:advisor advice-ref="txAdvice" pointcut-ref="service" order="2"/>
106         <aop:advisor advice-ref="dataSourceExchange" pointcut-ref="service" order="1"/>
107     </aop:config>
108 
109 </beans>

四、疑问

    多数据源切换是成功了,但牵涉到事务呢?单数据源事务是ok的,但如果多数据源需要同时使用一个事务呢?这个问题有点头大,网络上有人提出用atomikos开源项目实现JTA分布式事务处理。你怎么看?

五、dataSourceExchange 是怎样写的?

dataSourceExchange对应的类可以实现接口org.aopalliance.intercept.MethodInterceptor的invoke方法|@|@Override|@|public Object invoke(MethodInvocation invocation) throws Throwable {|@|   DataSource dataSource = invocation.getMethod().getAnnotation(DataSource.class); |@|   DataSourceHolder.setDataSource(dataSource.name());|@|   try {|@|     invocation.proceed();|@|   } catch (Exception ex) { |@|   }|@|   return null;|@|}|@|pointcut的expression也可以写成@annotation(com.xxx.DataSource)|@|使用的时候,只需要在方法上加上注解@DataSource就行了|@|@DataSource(name = DataSource.slave1)|@|public void insert(String name) {|@|}

原文地址:https://www.cnblogs.com/fnlingnzb-learner/p/9723708.html