spring 集成mybatis——多数据源切换(附带定时器的配置)

新建com.millery.utils包在其下新建DataSourceContextHolder类

package com.millery.utils;

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();  
    }  
}  

新建DataSourceContextHolder类

package com.millery.utils;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {  
    @Override  
    protected Object determineCurrentLookupKey() {  
        return DataSourceContextHolder.getDbType();  
    }  
}  

配置mybatis

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans"  
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:tx="http://www.springframework.org/schema/tx" 
xmlns:jpa="http://www.springframework.org/schema/data/jpa"   
xmlns:util="http://www.springframework.org/schema/util"  
xmlns:jaxws="http://cxf.apache.org/jaxws"  

xmlns:p="http://www.springframework.org/schema/p" 
xmlns:aop="http://www.springframework.org/schema/aop" 

xsi:schemaLocation="http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd     
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd

        http://www.springframework.org/schema/tx     
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd     
        http://www.springframework.org/schema/util  
        http://www.springframework.org/schema/util/spring-util-4.3.xsd 

        http://www.springframework.org/schema/aop     
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd   

        http://www.springframework.org/schema/data/jpa                           
        http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd        
        http://www.springframework.org/schema/beans                              
        http://www.springframework.org/schema/beans/spring-beans.xsd    

        http://cxf.apache.org/jaxws    
        http://cxf.apache.org/schemas/jaxws.xsd">

        <import resource="classpath:META-INF/cxf/cxf.xml"/>  
        <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>  
        <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/> 
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.hqgf" />
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>
    <!-- <util:properties id="APP_PROPERTIES" location="classpath:attendance.properties" local-override="true"/> -->
    <bean id="HrtestSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
        <property name="url" value="jdbc:sqlserver://172.69.1.236;DatabaseName=LongshineWebHr" />
        <property name="username" value="sa" />
        <property name="password" value="Hqmart88" />
    </bean>
    <bean id="HrSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
        <property name="url" value="jdbc:sqlserver://172.88.10.161;DatabaseName=LongshineWebHr " />
        <property name="username" value="sa" />
        <property name="password" value="Hqmart88" />
    </bean>
    <bean id="AttendanceSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://172.69.1.8:3306/hws_sqlservice?useUnicode\=true;characterEncoding\=utf-8" />
        <property name="username" value="root" />
        <property name="password" value="[email protected]" />
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="dataSource" class="com.millery.utils.DynamicDataSource">    
        <property name="targetDataSources">    
            <map key-type="java.lang.String">    
                <entry value-ref="HrtestSource" key="HrtestSource"></entry>    
                <entry value-ref="HrSource" key="HrSource"></entry>   
                <entry value-ref="AttendanceSource" key="AttendanceSource"></entry> 
            </map>    
        </property>    
        <property name="defaultTargetDataSource" ref="HrtestSource"></property><!-- 默认使用HrtestSource的数据源 -->  
    </bean>  

    <!-- 2. mybatis 的SqlSession 的工厂: SqlSessionFactoryBean -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource"/>  
        <property name="mapperLocations" value="classpath:com/hqgf/mapping/*.xml"/>  
    </bean> 

    <!-- 3. mybatis 自动扫描加载Sql 映射文件 : MapperScannerConfigurer -->  
    <!-- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.mapper"/>  
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>  
    </bean>  -->            

    <!-- 4. 事务管理 : DataSourceTransactionManager -->  
    <bean  id="txManager"   
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource"/>  
    </bean>   

    <!-- 5. 使用声明式事务 -->  
    <tx:annotation-driven transaction-manager="txManager" />  


  <!-- 数据抓取任务 -->
  <!-- 任务实体 -->
   <bean id="eleTaskBean" class="com.hqgf.attendanceupload.HwsTimeTask" /> 

  <bean id="eletasktimingmethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> 
    <property name="targetObject" ref="eleTaskBean" /> 
    <!-- targetMethod 配置定时执行的方法名 -->
    <property name="targetMethod" value="TimeTaskData" /> 
    <property name="concurrent" value="false" /> 
  </bean>

  <!-- 设置每天凌晨两点执行定时任务 -->
   <bean id="eleTaskTrigger"
    class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> 
    <property name="jobDetail" ref="eletasktimingmethod" /> 
    <property name="cronExpression" value="01 50 16 * * ?" /> 
  </bean>  


  <!-- 订制任务列表 -->
 <bean id="scheduler"
    class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
    <property name="triggers"> 
      <list> 
        <ref bean="eleTaskTrigger" /> 
      </list> 
    </property> 
  </bean>  
</beans>  

每个mapper调用之前

    @Override
    public String queryDept(String hr_dept_code) throws Exception {

        DataSourceContextHolder.setDbType("AttendanceSource");
        //注意这里在调用userMapper前切换到AttendanceSource的数据源 

        String attendanceid= getSqlSession().selectOne("com.hqgf.dao.IUploadAttendanceDao.queryDept",hr_dept_code);
        System.out.println("部门编码匹配成功__"+attendanceid);

        return attendanceid;

    }

数据库切换成功。

猜你喜欢

转载自blog.csdn.net/weixin_42388648/article/details/80578806