spring+springmvc+mybatis整合多数据源
项目结构图:
创建DataSourceContextHolder类
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setDbType(String dbType) {
contextHolder.set(dbType);
}
public static String getDbType() {
return ((String) contextHolder.get());
}
public static void clearDbType() {
contextHolder.remove();
}
}
创建DynamicDataSource类
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDbType();
}
}
创建读取数据库配置类ReadPropertyConfigurer
public class ReadPropertyConfigurer extends PropertyPlaceholderConfigurer {
//如果需要加密就重写这两个方法
@Override
protected String convertProperty(String propertyName,String propertyValue){
if(isEncryptPropertyVal(propertyName)){
return propertyValue;
}
return propertyValue;
}
private boolean isEncryptPropertyVal(String propertyName){
if(propertyName.contains("password")){
return true;
}else{
return false;
}
}
}
在resouce下创建applicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-autowire="byName">
<bean id="propertyConfigurer"
class="com.ssm.demo.datasource.ReadPropertyConfigurer">
<property name="locations">
<list>
<value>classpath:dbconfig.properties</value>
</list>
</property>
</bean>
<import resource="spring-bean.xml" />
</beans>
创建db.properties
#master
jdbc.mysql.driver=com.mysql.jdbc.Driver
jdbc.mysql.url=jdbc:mysql://127.0.0.1:3306/mysql?useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true&autoReconnect=true&allowMultiQueries=true
jdbc.mysql.username=root
jdbc.mysql.password=12345678
#master1
jdbc.mysql.demo.driver=com.mysql.jdbc.Driver
jdbc.mysql.demo.url=jdbc:mysql://127.0.0.1:3306/xxl_job?useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true&autoReconnect=true&allowMultiQueries=true
jdbc.mysql.demo.username=root
jdbc.mysql.demo.password=12345678
#============================================================================
jdbc.initialSize=6
jdbc.minIdle=20
#jdbc.maxIdle=15
jdbc.maxActive=180
#ms
jdbc.maxWait=15000
jdbc.defaultAutoCommit=false
jdbc.removeAbandoned=true
#s
jdbc.removeAbandonedTimeout=120
jdbc.testWhileIdle=true
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.numTestsPerEvictionRun=20
jdbc.minEvictableIdleTimeMillis=300000
jdbc.validationQuery=select 'x' from dual
jdbc.logAbandoned=true
jdbc.testOnBorrow=true
jdbc.testOnReturn=true
jdbc.poolPreparedStatements=false
jdbc.maxPoolPreparedStatementPerConnectionSize=50
jdbc.maxOpenPreparedStatements=20
创建spring-bean.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-lazy-init="false">
<!-- 支持注解的方式控制事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="base" class="com.alibaba.druid.pool.DruidDataSource" init-method="init">
<property name="url" value="${jdbc.mysql.url}" />
<property name="username" value="${jdbc.mysql.username}" />
<property name="password" value="${jdbc.mysql.password}" />
<property name="initialSize" value="${jdbc.initialSize}" />
<property name="minIdle" value="${jdbc.minIdle}" />
<property name="maxActive" value="${jdbc.maxActive}" />
<property name="maxWait" value="${jdbc.maxWait}" />
<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="${jdbc.validationQuery}" />
<property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
<property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
<property name="testOnReturn" value="${jdbc.testOnReturn}" />
<property name="poolPreparedStatements" value="${jdbc.poolPreparedStatements}" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="${jdbc.maxPoolPreparedStatementPerConnectionSize}" />
<property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
<property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
<property name="logAbandoned" value="${jdbc.logAbandoned}" />
<property name="filters" value="stat" />
</bean>
<bean id="demo" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" >
<property name="url" value="${jdbc.mysql.demo.url}" />
<property name="username" value="${jdbc.mysql.demo.username}" />
<property name="password" value="${jdbc.mysql.demo.password}" />
<property name="initialSize" value="${jdbc.initialSize}" />
<property name="minIdle" value="${jdbc.minIdle}" />
<property name="maxActive" value="${jdbc.maxActive}" />
<property name="maxWait" value="${jdbc.maxWait}" />
<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />
<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />
<property name="validationQuery" value="${jdbc.validationQuery}" />
<property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
<property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
<property name="testOnReturn" value="${jdbc.testOnReturn}" />
<property name="poolPreparedStatements" value="${jdbc.poolPreparedStatements}" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="${jdbc.maxPoolPreparedStatementPerConnectionSize}" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
<property name="logAbandoned" value="${jdbc.logAbandoned}" />
<property name="filters" value="stat" />
</bean>
<!-- 动态配置数据源 -->
<bean id ="dataSource" class= "com.ssm.demo.datasource.DynamicDataSource" >
<property name ="targetDataSources">
<map key-type ="java.lang.String">
<entry value-ref ="base" key= "base"></entry >
<entry value-ref ="demo" key= "demo"></entry >
</map >
</property >
<!-- 默认使用base的数据源 -->
<property name ="defaultTargetDataSource" ref= "base"></property >
</bean >
<!-- 创建SqlSessionFactory -->
<bean id ="sqlSessionFactory" class= "org.mybatis.spring.SqlSessionFactoryBean" >
<!-- 指定数据源 -->
<property name ="dataSource" ref="dataSource" />
<!-- 指定mybatis 的配置文件 -->
<property name ="configLocation" value= "classpath:mybatis-config.xml" />
<!--扫描pojo包,给pojo包下的类起别名-->
<property name="typeAliasesPackage" value="com.ssm.demo.pojo"></property>
<property name="mapperLocations">
<list>
<value>classpath:com/ssm/demo/mapper/task/*Mapper.xml</value>
<value>classpath:com/ssm/demo/mapper/user/*Mapper.xml</value>
</list>
</property>
</bean >
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置 Mapper 接口扫描-->
<bean class ="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name ="basePackage" value= "com.ssm.demo.mapper"></property >
</bean >
<!-- ================================事务相关控制================================================= -->
<tx:advice id="Advice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="insert*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="update*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="save*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="select*" propagation="SUPPORTS" />
<tx:method name="query*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>
<!-- 配置AOP -->
<aop:config >
<!--把事务控制再service层-->
<aop:pointcut expression ="execution(* com.ssm.demo.service..*.*(..))"
id= "pointcut" />
<aop:advisor advice-ref ="Advice" pointcut-ref="pointcut" />
</aop:config >
<!-- 事务控制结束 -->
</beans>
创建webMvcContext.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!--组件扫描,注解扫描-->
<context:component-scan base-package="com.ssm.demo" />
<!--处理器适配器-->
<!-- <mvc:default-servlet-handler/> -->
<mvc:annotation-driven/>
<!--配置视图解析器-->
<bean id="resource" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--释放静态资源-->
<mvc:default-servlet-handler/>
<!-- 启动对@AspectJ注解的支持 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
</beans>
修改web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Archetype Created Web Application</display-name>
<!--配置编码过滤器-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置spring核心监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--重新指定spring配置文件路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--springmvc核心servlet配置初始化的时候加载springmvc配置文件-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:webMvcContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
演示数据库切换
System.out.println(iUserSv.getUser("13101775857").toString());
//切换数据源
DataSourceContextHolder.setDbType("demo");
System.out.println(iTaskSv.getAllTask().toString());
//移除数据源使用默认数据源
DataSourceContextHolder.clearDbType();
System.out.println(iUserSv.getUser("15539920366").toString());