• spring+springMVC+mybatis项目中 多数据源的配置


    由于项目中需要进行数据迁移,需要连接两个 不同的数据库 ,所以百度了如何配置多数据源,记录一下!

    首先是配置文件中两个不同数据源,以及多数据源(用来在两个不同数据源之间切换)的配置,包括事物的配置,sqlSessionFactory的配置

    <bean id="posDataSource" class="com.alibaba.druid.pool.DruidDataSource"
            init-method="init" destroy-method="close">
            <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
            <property name="driverClassName" value="${pos.driverClass}" />
    
            <!-- 基本属性 url、user、password -->
            <property name="url" value="${pos.jdbcUrl}" />
            <property name="username" value="${pos.user}" />
            <property name="password" value="${pos.password}" />
    
            <!-- 配置初始化大小、最小、最大 -->
            <property name="initialSize" value="2" />
            <property name="minIdle" value="5" />
            <property name="maxActive" value="10" />
    
            <!-- 配置获取连接等待超时的时间 -->
            <property name="maxWait" value="60000" />
    
            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="60000" />
    
            <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            <property name="minEvictableIdleTimeMillis" value="300000" />
    
            <property name="validationQuery" value="SELECT 'x'" />
            <property name="testWhileIdle" value="true" />
            <property name="testOnBorrow" value="false" />
            <property name="testOnReturn" value="false" />
    
            <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
            <property name="poolPreparedStatements" value="false" />
            <property name="maxPoolPreparedStatementPerConnectionSize"
                value="20" />
    
            <!-- 配置监控统计拦截的filters -->
            <property name="filters" value="stat" />
        </bean>
    
        <bean id="sqlServerDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
            <property name="url" value="jdbc:sqlserver://XXX:XXX;DatabaseName=XXXX;useLOBs=false"/>
            <property name="username" value="XXX"/>
            <property name="password" value="XXX"/>
            <property name="initialSize" value="5"/>
            <property name="minIdle" value="5"/>
            <property name="maxIdle" value="20"/>
            <property name="maxActive" value="100"/>
            <property name="maxWait" value="10000"/>
            <property name="defaultAutoCommit" value="false"/>
            <property name="removeAbandoned" value="true"/>
            <property name="removeAbandonedTimeout" value="600"/>
            <property name="testWhileIdle" value="true"/>
            <property name="timeBetweenEvictionRunsMillis" value="60000"/>
            <property name="numTestsPerEvictionRun" value="20"/>
            <property name="minEvictableIdleTimeMillis" value="300000"/>
        </bean>
    
        <bean id="multipleDataSource" class="com.qinyi.pos.core.Configuration.MultipleDataSource">
            <property name="targetDataSources">
                <map key-type="java.lang.String">
                    <entry value-ref="posDataSource" key="posDataSource"/>
                    <entry value-ref="sqlServerDataSource" key="sqlServerDataSource"/>
                </map>
            </property>
            <property name="defaultTargetDataSource" ref="posDataSource"/>
        </bean>
    
        <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
        <bean id="posTransactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="multipleDataSource" />
            <qualifier value="pos"/>
        </bean>
    
        <!-- 可通过注解控制事务 -->
        <tx:annotation-driven transaction-manager="posTransactionManager" proxy-target-class="true" />
    
        <!-- 创建SqlSessionFactory,同时指定数据源 -->
        <bean id="posSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="multipleDataSource" />
            <property name="configLocation">
                <value>classpath:mybatis-config.xml</value>
            </property>
            <property name="mapperLocations" value="classpath*:/mapper/pos/*.xml" />
        </bean>

    然后是java代码的书写,用来切换数据源

      

    package com.qinyi.pos.core.Configuration;
    
    public class DataSourceContextHolder {
        private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
    
        public static final String DEFAULT_DATA_SOURCE="posDataSource"; //默认数据源
    
        public static final String READ_DATA_SOURCE="sqlServerDataSource";       //第二个数据源,
    
        /**
         * 设置数据源类型
         * @param dataSource 数据源名称
         */
        public static void setDataSource(String dataSource) {
            contextHolder.set(dataSource);
        }
    
        /**
         * 获取数据源名称
         */
        public static String getDataSource() {
            return contextHolder.get();
        }
    
        /**
         * 清除数据源名称
         */
        public static void clearDataSource() {
            contextHolder.remove();
        }
    }
    

      

    package com.qinyi.pos.core.Configuration;
    
    import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
    
    public class MultipleDataSource extends AbstractRoutingDataSource {
        @Override
        protected Object determineCurrentLookupKey() {
            return DataSourceContextHolder.getDataSource();
        }
    }

    接下来就可以开始使用了,可以在dao层调用方法之前,设置一下数据源(用完之后,记得将数据源给remove掉)

    @Override
    	public List<StockCode> testDataSource(StockCode stockCode) {
    		DataSourceContextHolder.setDataSource(DataSourceContextHolder.READ_DATA_SOURCE);
    		List getTestDataSource = posBaseDao.selectList("getTestDataSource");
    
    		DataSourceContextHolder.clearDataSource();
    		return getTestDataSource;
    	}
    

      

  • 相关阅读:
    One SQL to Rule Them All – an Efficient and Syntactically Idiomatic Approach to Management of Streams and Tables(中英双语)
    Spark 公共篇-InterfaceStability
    ANTLR v4 专业术语集
    Apache Spark as a Compiler: Joining a Billion Rows per Second on a Laptop(中英双语)
    Deep Dive into Spark SQL’s Catalyst Optimizer(中英双语)
    What’s new for Spark SQL in Apache Spark 1.3(中英双语)
    Scala 隐式(implicit)详解
    Introducing Apache Spark Datasets(中英双语)
    darknet-yolov3训练自己的数据集(转)
    NVIDIA显卡,显卡驱动版本,CUDA版本,cudnn版本之间兼容关系及如何选择
  • 原文地址:https://www.cnblogs.com/changeCode/p/9724157.html
Copyright © 2020-2023  润新知