配置多个数据源

1,spring-mybatis.xml

<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.2.xsd">

    <bean id="dataSource_meta" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close" >
          <property name="driverClassName" value="${jdbc_driverClassName}"/>
          <property name="url" value="${jdbc_url}"/>
          <property name="username" value="${jdbc_username}"/>
          <property name="password" value="${jdbc_password}"/>
          <!-- 配置初始化大小、最小、最大 -->
          <property name="initialSize" value="5" />
          <property name="minIdle" value="2" />
          <property name="maxActive" value="20" />
          <!-- 配置获取连接等待超时的时间 -->
          <property name="maxWait" value="60000" />
          <!-- 自动清除无用连接 -->
          <property name="removeAbandoned" value="true"/>
          <!-- 清除无用连接的等待时间 -->
          <property name="removeAbandonedTimeout" value="1800"/>
          <!-- 连接属性 -->
          <property name="connectionProperties" value="clientEncoding=UTF-8"/>
    </bean>

    <bean id="dataSource_read" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本属性 url、user、password -->
        <property name="url" value="${jdbc_url_read}" />
        <property name="username" value="${jdbc_username_read}" />
        <property name="password" value="${jdbc_password_read}" />
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="5" />
        <property name="minIdle" value="2" />
        <property name="maxActive" value="300" />
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="60000" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="validationQuery" value="SELECT now() from dual" />
        <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,wall-sql攻击 -->
        <property name="filters" value="mergeStat,wall" />
        <!-- 慢查询slowSqlMillis的缺省值为3000,也就是3秒 -->
        <property name="connectionProperties" value="druid.stat.slowSqlMillis=3000" />
        <property name="removeAbandoned" value="true" /> <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandonedTimeout" value="1800" /> <!-- 1800秒,也就是30分钟 -->
        <property name="logAbandoned" value="true" /> <!-- 关闭abanded连接时输出错误日志 -->
    </bean>

    <bean id="dynamicDataSource" class="cn.springmvc.util.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry value-ref="dataSource_read" key="dataSource_read"></entry>
                <entry value-ref="dataSource_meta" key="dataSource_meta" ></entry>
            </map>
        </property>
        <property name="defaultTargetDataSource" ref="dataSource_read">
        </property>
    </bean>

    <!-- mybatis文件配置,扫描所有mapper文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
         p:dataSource-ref="dynamicDataSource"
         p:configLocation="classpath:conf/mybatis-config.xml"
         p:mapperLocations="classpath:mapper/*.xml">
    </bean>

   <!-- spring与mybatis整合配置,扫描所有dao -->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
         p:basePackage="cn.springmvc.dao"
         p:sqlSessionFactoryBeanName="sqlSessionFactory">
   </bean>

   <!-- 对数据源进行事务管理 -->
   <bean id="transactionManager"
         class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
         p:dataSource-ref="dynamicDataSource"/>

</beans>


2,DynamicDataSource.java

package cn.springmvc.util;

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

/**
 * 配置多数据源工具类
 * @author Carl
 *
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

	@Override
	protected Object determineCurrentLookupKey() {
		return DatabaseContextHolder.getCustomerType();
	}

}

3,DatabaseContextHolder.java

package cn.springmvc.util;

/**
 * 配置多数据源控制类
 *
 * @author Carl
 */
public class DatabaseContextHolder {

    public static final String DATA_SOURCE_META = "dataSource_meta";
    public static final String DATA_SOURCE_READ = "dataSource_read";
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    public static void setCustomerType(String customerType) {
        contextHolder.set(customerType);
    }

    public static String getCustomerType() {
        return contextHolder.get();
    }

    public static void clearCustomerType() {
        contextHolder.remove();
    }

}

测试:

@RequestMapping(value = "insert/user2/{state}")
    public String insertUserById2(@PathVariable int state){
        //切换数据源
        DatabaseContextHolder.setCustomerType(DatabaseContextHolder.DATA_SOURCE_META);
        try {
            logger.info(state);
            User u = new User();
            u.setState(state);
            u.setNickname("张*");
            int ret = userService.insertUser(u);
            logger.info(ret);
        }finally {
            DatabaseContextHolder.clearCustomerType();
        }
        return "index";
    }






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值