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

在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. public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean

 

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


Java代码   收藏代码
  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()里:


Java代码   收藏代码
  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(),该方法返回需要使用的DataSource的key值,然后根据这个key从resolvedDataSources这个map里取出对应的DataSource,如果找不到,则用默认的resolvedDefaultDataSource。


Java代码   收藏代码
  1.         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.     } 

 

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


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


Java代码   收藏代码
  1. public class DynamicDataSourceHolder {
  2. // 线程局部变量(多线程并发设计,为了线程安全)
  3. private static final ThreadLocal<String> contextHolder = new ThreadLocal();  
  4.   
  5. // 设置数据源类型  
  6. public static void setDataSourceType(String dataSourceType) {  
  7.     Assert.notNull(dataSourceType, "DataSourceType cannot be null");  
  8.     contextHolder.set(dataSourceType);  
  9. }  
  10.   
  11. // 获取数据源类型  
  12. public static String getDataSourceType() {  
  13.     return (String) contextHolder.get();  
  14. }  
  15.   
  16. // 清除数据源类型  
  17. public static void clearDataSourceType() {  
  18.     contextHolder.remove();  
  19. }  
 

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

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


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

  

    <!-- 管理库数据源 -->
    <bean id="defaultDataSource" 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="initialSize" value="20" />
        <property name="maxActive" value="500" />
        <property name="maxIdle" value="500" />
        <property name="maxWait" value="500" />
        <property name="removeAbandoned" value="true"/>
        <property name="testWhileIdle" value="false" />
        <property name="testOnBorrow" value="true" />
        <property name="testOnReturn" value="false" />
        <property name="validationQuery" value="${jdbc.validationQuery}" />
        <property name="defaultAutoCommit" value="false" />
    </bean>

    <!-- 数据仓库数据源 -->
    <bean id="DWDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
        <property name="url" value="${jdbc.DW.url}" />
        <property name="username" value="${jdbc.DW.username}" />
        <property name="password" value="${jdbc.DW.password}" />

        <property name="initialSize" value="20" />
        <property name="maxActive" value="500" />
        <property name="maxIdle" value="500" />
        <property name="maxWait" value="500" />
        <property name="removeAbandoned" value="true"/>
        <property name="testWhileIdle" value="false" />
        <property name="testOnBorrow" value="true" />
        <property name="testOnReturn" value="false" />
        <property name="validationQuery" value="${jdbc.validationQuery}" />
        <property name="defaultAutoCommit" value="false" />
    </bean>
    
    <!-- ODS数据库数据源 -->
    <bean id="ODSDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
        <property name="url" value="${jdbc.ODS.url}" />
        <property name="username" value="${jdbc.ODS.username}" />
        <property name="password" value="${jdbc.ODS.password}" />

        <property name="initialSize" value="5" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="20" />
        <property name="maxWait" value="3000" />
        <property name="removeAbandoned" value="true"/>
        <property name="testWhileIdle" value="false" />
        <property name="testOnBorrow" value="true" />
        <property name="testOnReturn" value="false" />
        <property name="validationQuery" value="${jdbc.validationQuery}" />
        <property name="defaultAutoCommit" value="false" />
    </bean>

    <bean id="dataSource" class="com.eryansky.common.datasource.DynamicDataSource">
        <property name="defaultTargetDataSource" ref="defaultDataSource"/>
        <property name="targetDataSources">
            <map>
                <!-- 注意这里的value是和上面的DataSource的id对应,key要和下面的DataSourceContextHolder中的常量对应 -->
                <entry value-ref="defaultDataSource" key="defaultDataSource"/>
                <entry value-ref="DWDataSource" key="DWDataSource"/>
                <entry value-ref="ODSDataSource" key="ODSDataSource"/>
            </map>
        </property>
    </bean>

   <!-- Hibernate切面拦截器 -->
    <bean id="hibernateAspectInterceptor" class="com.jfit.core.HibernateAspectInterceptor" />

    <!-- Hibernate配置 -->
    <bean id="defaultSessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="entityInterceptor" ref="hibernateAspectInterceptor"/>
        <property name="namingStrategy">
            <bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>


                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
                <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
                <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
                <prop key="net.sf.ehcache.configurationResourceName">${net.sf.ehcache.configurationResourceName}</prop>
                <prop key="hibernate.jdbc.batch_size">0</prop>
                <!--<prop key="hibernate.use_nationalized_character_data">false</prop>-->
                <prop key="hibernate.search.default.indexBase">${hibernate.search.default.indexBase}</prop>
            </props>
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.xxxx.modules.*.entity</value>
            </list>
        </property>
    </bean>



4.数据源注解定义

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {

    String value();
}



5、配置注解切换数据源

   <!--Spring的事务管理是与数据源绑定的,一旦程序执行到事务管理的那一层(如service)的话,由于在进入该层之前事务已经通过拦截器开启,
        所以请在Controller层设置注解(数据源/SessionFactory)切换、或编码方式-->
    <!--动态数据源切换AOP拦截器-->
    <bean name="dataSourceMethodInterceptor" class="com.eryansky.common.datasource.DataSourceMethodInterceptor"></bean>
    <!-- 参与动态切换数据源的切入点对象 (切入点对象,确定何时何地调用拦截器) -->
    <bean id="methodDataSourcePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
        <!-- 配置缓存aop切面 -->
        <property name="advice" ref="dataSourceMethodInterceptor" />
        <!-- 配置哪些方法参与缓存策略 -->
        <!--
            .表示符合任何单一字元
            ###  +表示符合前一个字元一次或多次
            ###  *表示符合前一个字元零次或多次
            ###  \Escape任何Regular expression使用到的符号
        -->
        <!-- .*表示前面的前缀(包括包名) 表示print方法-->
        <property name="patterns">
            <list>
                <value>com.xxx.modules.cms.web.*Controller.*(..)</value>
                <value>com.xxx.modules.md.web.*Controller.*(..)</value>
            </list>
        </property>
    </bean>


6.注解的方法拦截器代码

/**
 * 多数据源动态配置拦截器
 *
 */
public class DataSourceMethodInterceptor implements MethodInterceptor, InitializingBean {

    private Logger logger = LoggerFactory.getLogger(DataSourceMethodInterceptor.class);

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Class<?> clazz = invocation.getThis().getClass();
        String className = clazz.getName();
        if (ClassUtils.isAssignable(clazz, Proxy.class)) {
            className = invocation.getMethod().getDeclaringClass().getName();
        }
        String methodName = invocation.getMethod().getName();
        Object[] arguments = invocation.getArguments();
        logger.trace("execute {}.{}({})", className, methodName, arguments);

        invocation.getMethod();
        DataSource classDataSource = ReflectionUtils.getAnnotation(invocation.getThis(), DataSource.class);
        DataSource methodDataSource = ReflectionUtils.getAnnotation(invocation.getMethod(), DataSource.class);
        if(methodDataSource != null){
            DataSourceContextHolder.setDataSourceType(methodDataSource.value());
        }else if(classDataSource != null){
            DataSourceContextHolder.setDataSourceType(classDataSource.value());
        }else {
            DataSourceContextHolder.clearDataSourceType();
        }

        Object result = invocation.proceed();
        return result;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    }
}

7.使用

    @RequestMapping(value = {"datagrid"})
    @ResponseBody
    @DataSource("DWDataSource")//切换到DATASOURCE_DW数据源
    public Datagrid<Map> datagrid(@RequestParam(value="p_organId",required=false) String organId){
     //省略
    }



完结。。。


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
下面是使用 AbstractRoutingDataSource 和 MyBatis 拦截器实现动态切换数据源的示例代码: 首先,需要自定义一个继承 AbstractRoutingDataSource 的类,并实现 determineCurrentLookupKey 方法,该方法用于返回当前数据源的 key: ```java public class DynamicDataSource extends AbstractRoutingDataSource { private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<>(); public static void setDataSourceKey(String key) { dataSourceKey.set(key); } @Override protected Object determineCurrentLookupKey() { return dataSourceKey.get(); } } ``` 在 Spring 配置文件中需要配置两个数据源,并将 DynamicDataSource 设置为默认数据源: ```xml <bean id="dataSource1" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db1"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <bean id="dataSource2" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db2"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <bean id="dynamicDataSource" class="com.example.DynamicDataSource"> <property name="defaultTargetDataSource" ref="dataSource1"/> <property name="targetDataSources"> <map> <entry key="db1" value-ref="dataSource1"/> <entry key="db2" value-ref="dataSource2"/> </map> </property> </bean> ``` 接下来,需要实现一个继承于 MyBatis 的 Interceptor 接口的拦截器类,该类用于在执行 SQL 语句前切换数据源: ```java @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) public class DynamicDataSourceInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget(); MetaObject metaObject = SystemMetaObject.forObject(statementHandler); MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement"); String dataSourceKey = getDataSourceKey(mappedStatement); if (dataSourceKey != null) { DynamicDataSource.setDataSourceKey(dataSourceKey); } return invocation.proceed(); } private String getDataSourceKey(MappedStatement mappedStatement) { String dataSourceKey = null; // 从 Mapper 方法上获取数据源 key if (mappedStatement != null) { String id = mappedStatement.getId(); if (id.startsWith("com.example.mapper1")) { dataSourceKey = "db1"; } else if (id.startsWith("com.example.mapper2")) { dataSourceKey = "db2"; } } return dataSourceKey; } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { // do nothing } } ``` 最后,需要在 Spring 配置文件中配置该拦截器: ```xml <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dynamicDataSource"/> <property name="plugins"> <array> <bean class="com.example.DynamicDataSourceInterceptor"/> </array> </property> </bean> ``` 这样,就可以在 Mapper 方法上使用 @DataSource("db1") 或 @DataSource("db2") 注解来指定使用哪个数据源了。例如: ```java @DataSource("db1") List<User> getUserList(); @DataSource("db2") int addUser(User user); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值