springmvc 配置多個數據源,並動態切換


前言:工作中經常會有兩個數據源的情況,所以記錄一下。這里測試兩個數據源,給出流程和代碼。

首先:配置兩個數據源

    <description>配置mybatis數據源</description>

    <!-- 加載配置文件 -->
    <context:property-placeholder location="classpath*:conf/system/*.properties"/>

    <!-- 需要 commons.dbcp 包 -->
    <bean id="firstDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.datasourceurl}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>

        <property name="maxActive" value="100"/>
        <property name="maxIdle" value="20"/>
        <property name="maxWait" value="1000"/>
        <property name="defaultAutoCommit" value="true"/>
        <property name="removeAbandoned" value="true"/>
        <property name="removeAbandonedTimeout" value="60"/>
        <property name="validationQuery" value="select count(*) from dual"/>
        <property name="testOnBorrow" value="true"/>
        <property name="testOnReturn" value="true"/>
        <property name="testWhileIdle" value="true"/>
    </bean>

    <!--數據源二-->
    <bean id="secondDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${second.db.driver}"/>
        <property name="url" value="${second.db.datasourceurl}"/>
        <property name="username" value="${second.db.username}"/>
        <property name="password" value="${second.db.password}"/>

        <property name="maxActive" value="100"/>
        <property name="maxIdle" value="20"/>
        <property name="maxWait" value="1000"/>
        <property name="defaultAutoCommit" value="true"/>
        <property name="removeAbandoned" value="true"/>
        <property name="removeAbandonedTimeout" value="60"/>
        <property name="validationQuery" value="select count(*) from dual"/>
        <property name="testOnBorrow" value="true"/>
        <property name="testOnReturn" value="true"/>
        <property name="testWhileIdle" value="true"/>
    </bean>

然后寫一個數據源持有類

package com.yule.system.datasource;

/**
 * 數據源持有類
 * @author yule
 * @date 2018/9/28 19:34
 */
public class DataSourceHolder {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    /**
     * @Description: 設置數據源類型
     * @param dataSourceType  數據庫類型
     * @return void
     * @throws
     */
    public static void setDataSourceType(String dataSourceType) {
        contextHolder.set(dataSourceType);
    }

    /**
     * @Description: 獲取數據源類型
     * @return String
     * @throws
     */
    public static String getDataSourceType() {
        return contextHolder.get();
    }

    /**
     * @Description: 清除數據源類型
     * @return void
     * @throws
     */
    public static void clearDataSourceType() {
        contextHolder.remove();
    }

}

然后:寫一個數據源路由類

package com.yule.system.datasource;

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

/**
 * 路由類
 * @author yule
 * @date 2018/9/28 19:29
 */
public class RoutingDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceHolder.getDataSourceType();
    }
}

然后:配置數據源路由,class指定剛才的路由類

    <!--配置數據源路由-->
    <bean id="dataSource" class="com.yule.system.datasource.RoutingDataSource">
        <!-- 為targetDataSources注入兩個數據源 -->
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry key="db1" value-ref="firstDataSource"/>
                <entry key="db2" value-ref="secondDataSource"/>
            </map>
        </property>
        <!-- 為指定數據源RoutingDataSource注入默認的數據源-->
        <property name="defaultTargetDataSource" ref="firstDataSource"/>
    </bean>

 然后:配置事務

    <!-- 自動注冊service 必須在配置事務之上,否則@Transactional不起作用-->
    <context:component-scan base-package="com.yule">
        <context:include-filter type="regex" expression=".*\.service\..*" />
    </context:component-scan>

    <!--配置事務-->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 支持注解形式 enable transaction annotation support -->
    <tx:annotation-driven transaction-manager="txManager" />

然后:整合 spring 合 mybatis

    <!-- mybatis為spring提供的jar,其配置時不支持正則表達式配置 -->
    <bean id="mySqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.yule.*.entity,com.yule.*.*.entity,com.yule.*.*.*.entity"/>
        <property name="configLocation" value="classpath:/mybatis/system/mybatis-configuration.xml"/>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.yule.*.dao,com.yule.*.*.dao,com.yule.*.*.*.dao"/>
        <property name="sqlSessionFactoryBeanName" value="mySqlSessionFactory"/>
    </bean>

最后:使用方法

//獲取數據源類型
DataSourceHolder.getDataSourceType();
//設置為 db1 的數據源
DataSourceHolder.setDataSourceType("db1");
//設置為 db2 的數據源
DataSourceHolder.setDataSourceType("db2");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM