美文网首页高并发编程
Spring4 + Mybatis3 多数据源配置与调用举例

Spring4 + Mybatis3 多数据源配置与调用举例

作者: nextbang | 来源:发表于2017-01-16 17:33 被阅读114次

    后端使用数据库提供服务时,遇到性能问题,有时会采用分库分表的方式(当然可以用ES集群代替传统DB)来降低单台服务器压力,提高整体吞吐量。而分库就会有多数据源的问题,下面举例说明下在Spring4 + MyBatis3的情况下,如何连接多个数据库。

    1.配置数据库属性文件db.properties(针对dbcp连接池)

    initialSize=20
    maxActive=200
    maxIdle=20
    minIdle=1
    maxWait=60000
    
    data1.driver=com.mysql.jdbc.Driver
    data1.url=jdbc:mysql://localhsot:3306/test
    data1.username=test
    data1.password=123456
    
    data2.driver=com.mysql.jdbc.Driver
    data2.url=jdbc:mysql://localhsot:3307/test
    data2.username=test
    data2.password=123456
    
    

    2.Spring配置文件(重点dynamicDataSource,事务采用拦截器方式,并支持@Transcational注解方式)

    <?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/tx
                            http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    
        <!-- 数据源1:dataSource1-->
        <bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource"
              destroy-method="close">
            <property name="driverClassName" value="${data1.driver}" />
            <property name="url" value="${data1.url}" />
            <property name="username" value="${data1.username}" />
            <property name="password" value="${data1.password}" />
            <!-- 初始化连接大小 -->
            <property name="initialSize" value="${initialSize}"></property>
            <!-- 连接池最大数量 -->
            <property name="maxActive" value="${maxActive}"></property>
            <!-- 连接池最大空闲 -->
            <property name="maxIdle" value="${maxIdle}"></property>
            <!-- 连接池最小空闲 -->
            <property name="minIdle" value="${minIdle}"></property>
            <!-- 获取连接最大等待时间 -->
            <property name="maxWait" value="${maxWait}"></property>
        </bean>
        <!-- 数据源2:dataSource2-->
        <bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource"
              destroy-method="close">
            <property name="driverClassName" value="${data2.driver}" />
            <property name="url" value="${data2.url}" />
            <property name="username" value="${data2.username}" />
            <property name="password" value="${data2.password}" />
            <!-- 初始化连接大小 -->
            <property name="initialSize" value="${initialSize}"></property>
            <!-- 连接池最大数量 -->
            <property name="maxActive" value="${maxActive}"></property>
            <!-- 连接池最大空闲 -->
            <property name="maxIdle" value="${maxIdle}"></property>
            <!-- 连接池最小空闲 -->
            <property name="minIdle" value="${minIdle}"></property>
            <!-- 获取连接最大等待时间 -->
            <property name="maxWait" value="${maxWait}"></property>
        </bean>
        <!-- 多数据源bean创建 -->
        <bean id="dynamicDataSource" class="com.baidu.utils.DynamicDataSource">
            <property name="targetDataSources">
                <map key-type="java.lang.String">
                    <!-- 指定lookupKey和与之对应的数据源 -->
                    <entry key="dataSource" value-ref="dataSource"></entry>
                    <entry key="dataSource2" value-ref="dataSource2"></entry>
                </map>
            </property>
            <!-- 这里可以指定默认的数据源 -->
            <property name="defaultTargetDataSource" ref="dataSource" />
        </bean>
    
    
        <!-- 自动扫描mapping.xml文件 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- <property name="dataSource" ref="dataSource" /> -->
            <property name="dataSource" ref="dynamicDataSource" />
            <property name="mapperLocations" value="classpath:com/baidu/mapper/*.xml"></property>
        </bean>
    
        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!--basePackage指定要扫描的包,在此包之下的映射器都会被搜索到。 可指定多个包,包与包之间用逗号或分号分隔 -->
            <property name="basePackage" value="com.baidu.mapper" />
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        </bean>
    
    
        <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
        <bean id="txManager"
              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dynamicDataSource" />
        </bean>
    
        <!--声明式事务配置-->
        <tx:annotation-driven transaction-manager="txManager" />
        <!--需要扫描的包-->
        <context:component-scan base-package="com.baidu" />
    
        <!-- 拦截器方式配置事务 -->
        <tx:advice id="transactionAdvice" transaction-manager="txManager">
            <tx:attributes>
                <tx:method name="get*" propagation="NOT_SUPPORTED" />
                <tx:method name="query*" propagation="NOT_SUPPORTED" />
                <tx:method name="insert*" propagation="REQUIRED" />
                <tx:method name="update*" propagation="REQUIRED" />
                <tx:method name="delete*" propagation="REQUIRED" />
                <tx:method name="*" propagation="SUPPORTS" />
            </tx:attributes>
        </tx:advice>
        <aop:config>
            <aop:pointcut id="transactionPointcut" expression="execution(* com.baidu.service..*Impl.*(..))" />
            <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
        </aop:config>
    
    
    </beans>  
    

    3.实现DynamicDataSource类(需继承AbstractRoutingDataSource;使用ThreadLocal保存当前线程连接设置,解决多线程相互干扰问题)

    package com.baidu.utils;
    
    import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
    
    public class DynamicDataSource extends AbstractRoutingDataSource {
        private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>();
    
        public static void setDataSourceKey(String dataSource) {
            dataSourceKey.set(dataSource);
        }
    
        @Override
        protected Object determineCurrentLookupKey() {
            return dataSourceKey.get();
        }
    }
    

    4.调用示例

        @Autowired
        InvestorMapper investorMapper;
        
        public List<Investor> queryInvestors(String epId) throws Exception {
            /* 如果用dataSource1,则不需要调用setDataSource */
            DynamicDataSource.setDataSource("dataSource2");
            return investorMapper.queryInvestorsByEpId(epId);
        }
    

    相关文章

      网友评论

        本文标题:Spring4 + Mybatis3 多数据源配置与调用举例

        本文链接:https://www.haomeiwen.com/subject/tpjpbttx.html