http://blog.csdn.net/yichenlian/article/details/37055393

来源:互联网 发布:软件研发工程师待遇 编辑:程序博客网 时间:2024/06/05 10:54

由于系统有根据方法名实现动态切换数据源的需求,所以研究了下spring的动态切换数据源方式,然后和mybatis集成。

主要使用到了c3p0连接池、mybatis、spring(aop切面)、自定义拦截器

      1.首先定义数据源,我的数据源很多,只拿几个做例子;

  <context:property-placeholder ignore-unresolvable="true"          

  location="classpath*:/conf/dbpool.properties" /> 
        <bean id="dataSourceUserCenter_master" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> 
            <property name="driverClass"> 
                <value>${driverClassName}</value> 
            </property> 
            <property name="jdbcUrl"> 
                <value>${usercenter_master}</value> 
            </property> 
            <property name="user"> 
                <value>${username}</value> 
            </property> 
            <property name="password"> 
                <value>${password}</value> 
            </property> 
            <!--连接池中保留的最小连接数。Default: 5 --> 
            <property name="minPoolSize"> 
                <value>${minPoolSize}</value> 
            </property> 
            <!--连接池中保留的最大连接数。Default: 15 --> 
            <property name="maxPoolSize"> 
                <value>${maxPoolSize}</value> 
            </property> 
            <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 10 --> 
            <property name="initialPoolSize"> 
                <value>${initialPoolSize}</value> 
            </property> 
            <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> 
            <property name="acquireIncrement"> 
                <value>${acquireIncrement}</value> 
            </property> 
            <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> 
            <property name="maxIdleTime"> 
                <value>${maxIdleTime}</value> 
            </property> 
            <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 
              属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 
              如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0--> 
            <property name="maxStatements"> 
                <value>${maxStatements}</value> 
            </property> 
            <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> 
            <property name="idleConnectionTestPeriod"> 
                <value>${idleConnectionTestPeriod}</value> 
            </property> 
            <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> 
            <property name="acquireRetryAttempts"> 
                <value>${acquireRetryAttempts}</value> 
            </property> 
            <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 
              保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 
              获取连接失败后该数据源将申明已断开并永久关闭。Default: false--> 
            <property name="breakAfterAcquireFailure"> 
                <value>${breakAfterAcquireFailure}</value> 
            </property> 
            <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 
              时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 
              等方法来提升连接测试的性能。Default: false --> 
            <property name="testConnectionOnCheckout"> 
                <value>${testConnectionOnCheckout}</value> 
            </property> 
        </bean> 
         
        <bean id="dataSourceUserCenter_slave" parent="dataSourceUserCenter_master"> 
            <property name="jdbcUrl"> 
                <value>${usercenter_slave}</value> 
            </property> 
            <property name="user"> 
                <value>${username}</value> 
            </property> 
            <property name="password"> 
                <value>${password}</value> 
            </property> 
        </bean> 
         
         <bean id="dataSourceTest_slave" parent="dataSourceUserCenter_master"> 
            <property name="jdbcUrl"> 
                <value>${test_slave}</value> 
            </property> 
            <property name="user"> 
                <value>${username}</value> 
            </property> 
            <property name="password"> 
                <value>${password}</value> 
            </property> 
        </bean> 


2.对数据源进行整合包装,便于统一管理。

 <bean id="multipleDataSource" class="com.test.interceptor.datasource.MultipleDataSource"> 
    <property name="defaultTargetDataSource" ref="dataSourceUserCenter_master"/> 
    <property name="targetDataSources"> 
        <map> 
            <!-- 需要注意这里的key值与实现类里面的常量值要一样 --> 
            <entry value-ref="dataSourceUserCenter_master" key="UserCenter_master"/> 
            <entry value-ref="dataSourceUserCenter_slave" key="UserCenter_slave"/> 
            <entry value-ref="dataSourceTest_slave" key="Test_slave"/> 
        </map> 
    </property> 
</bean>

其中

com.test.interceptor.datasource.MultipleDataSource

实现了spring的AbstractRoutingDataSource类,故需用切换数据源的能力。defaultTargetDataSource是默认数据源、targetDataSources是所有数据源集合,默认数据源也要放置进来。其中每个entry的key要与java类中的常量相同。


3.和mybatis集成


<bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean"
          p:dataSource-ref="multipleDataSource"
          p:configLocation="classpath:conf/mybatis-config.xml"
          p:mapperLocations="classpath*:mapper/*.xml"/>


4.aop指向进行数据源切换的处理过滤器


<!-- 启用aop注解 -->
 <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

    <!-- 配置一个拦截器对象,处理具体的切换数据源的业务 -->
    <bean id="dataSourceMethodInterceptor" class="com.test.interceptor.DataSourceMethodInterceptor"/>
   
    <!-- 参与动态切换数据源的切入点对象 (切入点对象,确定何时何地调用拦截器) -->
    <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
        <!-- 配置缓存aop切面 -->
        <property name="advice" ref="dataSourceMethodInterceptor" />
        <!-- .*表示前面的前缀(包括包名) 表示print方法-->
        <property name="patterns">
            <list>
            <value>com.test.*.service.impl.*Service*\.*.*</value>
            </list>
        </property>
    </bean>


如上配置,扫描所有Service类中的方法,然后根据一定的规范来决定切换成哪个数据源。


  5.MultipleDataSource.java


public class MultipleDataSource extends AbstractRoutingDataSource{

      @Override
     protected Object determineCurrentLookupKey() {
     return DataSourceContextHandler.getDataSourceContext();
    }

}


   6.DataSourceContextHandler.java


/**
  * 线程局部变量,只为该线程服务
  */
 private final static ThreadLocal<String> contextHandler = new ThreadLocal<String>();
 
 /**
  * 设置该线程数据源id
  * @param dataSourceType
  */
 public static void setDataSourceContext(String dataSourceType){
  contextHandler.set(dataSourceType);
 }
 /**
  * 得到该线程数据源id
  * @return
  */
 public static String getDataSourceContext(){
  return contextHandler.get();
 }
 /**
  * 清除该线程的数据源变量值
  */
 public static void clearDataSourceContext(){
  contextHandler.remove();
 }


 7.DataSourceMethodInterceptor.java


        @Override
 public void afterPropertiesSet() throws Exception {
  logger.info("after properties set ...");
 }

 @Override
 public Object invoke(MethodInvocation invocation) throws Throwable {
  String dbname=....
        if (StringUtils.isNotBlank(dbname)) {
         if(isSlave){
          DataSourceContextHandler.setDataSourceContext(dbname+"_slave");
         }else{
          DataSourceContextHandler.setDataSourceContext(dbname+"_master");
         }
        }else{
         DataSourceContextHandler.clearDataSourceContext();
        }
        Object result = invocation.proceed();
        return result;
 }


在invoke方法中根据自定义的规则完成了数据源的选择。




0 0
原创粉丝点击