Spring Boot+Mybatis动态数据源配置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_22498277/article/details/75635589

数据源配置:

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- ===============只读数据源的配置=============== -->
    <bean id="dataSourceRead" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
          p:name="bosscenter" p:url="${jdbc.read.url}" p:username="${jdbc.read.username}"
          p:password="${jdbc.read.password}" p:maxActive="10" p:maxIdle="5"
          p:minIdle="5" p:initialSize="5" p:testOnBorrow="true" p:poolPreparedStatements="false"
          p:validationQuery="SELECT 1" p:filters="stat,config,wall" p:connectProperties="druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000"
          p:connectionProperties="config.decrypt=true" />

    <!-- ===============可写数据源的配置=============== -->
    <bean id="dataSourceWrite" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
          p:name="bosscenter" p:url="${jdbc.write.url}" p:username="${jdbc.write.username}"
          p:password="${jdbc.write.password}" p:maxActive="10" p:maxIdle="5"
          p:minIdle="5" p:initialSize="5" p:testOnBorrow="true" p:poolPreparedStatements="false"
          p:validationQuery="SELECT 1" p:filters="stat,config,wall" p:connectProperties="druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000"
          p:connectionProperties="config.decrypt=false" />

    <bean id="dynamicDataSource" class="com.aa.boss.policy.rpc.dbservice.dao.DynamicDataSource" primary="true">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <!--通过不同的key决定用哪个dataSource-->
                <entry value-ref="dataSourceRead" key="dataSourceRead"></entry>
                <entry value-ref="dataSourceWrite" key="dataSourceWrite"></entry>
            </map>
        </property>
        <!--设置默认的dataSource-->
        <property name="defaultTargetDataSource" ref="dataSourceRead">
        </property>
    </bean>

    <!-- define the SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dynamicDataSource" />
        <property name="mapperLocations" value="classpath:policyholdersmybatis/*.xml">
        </property>
        <property name="typeAliasesPackage" value="com.aa.boss.policy.rpc.api.pojo" />
        <property name="configLocation" value="classpath:mybatis.xml" />
    </bean>

    <!-- scan for mappers and let them be autowired -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
          id="mapperScannerConfigurer">
        <property name="basePackage" value="com.aa.boss.policy.rpc.dbservice.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

</beans>

在application.proopertis中配置多数据源连接信息

jdbc.read.driverClassName=com.mysql.jdbc.Driver
jdbc.read.url=jdbc:mysql://111111/11?useUnicode=true&characterEncoding=utf8
jdbc.read.username=111
jdbc.read.password=

jdbc.write.driverClassName=com.mysql.jdbc.Driver
jdbc.write.url=jdbc:mysql://111111/11?useUnicode=true&characterEncoding=utf8
jdbc.write.username=111
jdbc.write.password=11
定义一个DBContextHolder, 用于保存当前线程使用的数据源名:
import org.springframework.util.StringUtils;

/**
 * Created by lfd on 2017/7/7.
 */
public class DBContextHolder {
    public static final String DATA_SOURCE_READ = "dataSourceRead";
    public static final String DATA_SOURCE_WRITE = "dataSourceWrite";
    //用ThreadLocal来设置当前线程使用哪个dataSource
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
    public static void setDBType(String DBType) {
        contextHolder.set(DBType);
    }
    public static String getDBType() {
        String dataSource = contextHolder.get();
        if (StringUtils.isEmpty(dataSource)) {
            return DATA_SOURCE_READ;
        }else {
            return dataSource;
        }
    }
    public static void clearDBType() {
        contextHolder.remove();
    }
}
自定义一个 javax.sql.DataSource接口的实现,只需要继承Spring实现好的父类 AbstractRoutingDataSource即可

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

/**
 * Created by liufangda on 2017/7/7.
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DBContextHolder.getDBType();
    }
}
最后在你需要用到的接口的Controller层加入这么一句代码

DBContextHolder.setDBType(DBContextHolder.DATA_SOURCE_WRITE);
这时你这个接口用的就是 dataSourceWrite数据源,由于我在上面的配置中配置了默认的dataSource,所以你不加这句代码默认是会用 dataSourceRead数据源的

猜你喜欢

转载自blog.csdn.net/qq_22498277/article/details/75635589