SSM配置多数据源
一直以来用的都是mysql数据库,后来有将mysql数据库切换为sqlite,现在这个项目需要同时配置这两个数据源,基于别人的基础整理一个配置多数源的框架。仅供参考
导包
如果同时想用mysql 和sqlite,首先导入连接这两个数据库需要的jar包
mysql驱动包
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
sqlite驱动包
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>
</dependency>
配置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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- 加载数据库配置文件 -->
<context:property-placeholder location="classpath:db/Mysql.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>${driverClassName}</value>
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${dbUserName}</value>
</property>
<property name="password">
<value>${dbPassword}</value>
</property>
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
<property name="validationQuery" value="SELECT 1 FROM DUAL" />
</bean>
<!-- 配置SqlSessionFctory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath:mapper/*.Mapper.xml" />
<property name="dataSource" ref="dataSource" />
<property name="plugins">
<bean class="com.sys.common.PaginationInterceptor" />
</property>
</bean>
<!-- SqlSessionTemplate 是 MyBatis-Spring 的核心 -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<!-- Spring事务控制(txManager) -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- enable transaction annotation support -->
<tx:annotation-driven transaction-manager="txManager" />
</beans>
配置多个数据源
<?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:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<!-- 加载数据库配置文件 -->
<context:property-placeholder location="classpath:db/Mysql.properties" />
<bean id="dataSourceMysql" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>${driverClassName}</value>
</property>
<property name="url">
<value>${url}</value>
</property>
<property name="username">
<value>${dbUserName}</value>
</property>
<property name="password">
<value>${dbPassword}</value>
</property>
</bean>
<!--数据库sqlite连接池 -->
<bean id="dataSourceSqlite" class="org.apache.commons.dbcp.BasicDataSource">
<!-- 指定连接数据库的驱动 -->
<property name="driverClassName" value="org.sqlite.JDBC" />
<!-- 指定连接数据库的URL sqlite使用绝对路径 -->
<property name="url" value="jdbc:sqlite:E:/sqlite/kanban.db" />
</bean>
<bean id="dataSource" class="com.sys.dynamic.database.DynamicDataSource">
<!--默认数据源 -->
<property name="defaultTargetDataSource" ref="dataSourceSqlite" />
<property name="targetDataSources">
<map key-type="java.lang.String">
<!--这里是上面数据源配置的bean id -->
<entry key="dataSourceMysql" value-ref="dataSourceMysql" />
<entry key="dataSourceSqlite" value-ref="dataSourceSqlite" />
</map>
</property>
</bean>
<!-- 配置SqlSessionFctory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath:mapper/*.xml" />
<property name="dataSource" ref="dataSource" />
<property name="plugins">
<bean class="com.sys.common.PaginationInterceptor" />
</property>
</bean>
<!-- SqlSessionTemplate 是 MyBatis-Spring 的核心 -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<!-- Spring事务控制(txManager) -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- enable transaction annotation support -->
<tx:annotation-driven transaction-manager="txManager" />
<!-- 配置mybatis mapper接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.sys.dao" />
<property name="sqlSessionTemplateBeanName" value="sqlSessionTemplate" />
</bean>
</beans>
配置 spring-context.xml
增加切面注入的配置
<!--基于aspectj注解的配置文件在spring中的配置-->
<aop:aspectj-autoproxy expose-proxy="true"/>
<!--对这里加以改动,直接在类中进行配置-->
<!--设置切面进行拦截-->
<aop:config>
<!--设置事务的优先级-->
<aop:aspect ref="dataSwitchAop" order="0">
<!--拦截所有的service的方法-->
<!--当然也可以拦截Controller方法,这里设置的是拦截service-->
<aop:pointcut id="dataSourcePointcut" expression="execution(* com.sys.service.*Service..*(..))"/>
<aop:before method="intercept" pointcut-ref="dataSourcePointcut"/>
<aop:after method="clearDataSource" pointcut-ref="dataSourcePointcut"/>
</aop:aspect>
</aop:config>
<!--如果要设置拦截controller方法的话需要将参数设置为true,启动cligb代理-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
配置多个数据源的原理
利用spring的切面注入,在service层或者controller层进行拦截切换数据源
package com.sys.dynamic.database;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Documented
public @interface DataSource {
String value() default "";
}
package com.sys.dynamic.database;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
//第一个类,我自定义的类,这个类还需要注入到spring中进行配置
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDataSource();
}
}
package com.sys.dynamic.database;
public class DynamicDataSourceHolder {
//private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>();
private static final ThreadLocal<String> dataSourceKey = new ThreadLocal<String>();
public static String getDataSource() {
return dataSourceKey.get();
}
public static void setDataSource(String dataSource) {
dataSourceKey.set(dataSource);
}
public static void clearDataSource() {
dataSourceKey.remove();
}
}
package com.sys.dynamic.database;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
@Component
public class DataSwitchAop {
/**
* 拦截目标方法,获取由@DataSource指定的数据源标识,设置到线程存储中以便切换数据源
*
* @param point
* @throws Exception
*/
public void intercept(JoinPoint point) throws Exception {
System.out.println("==========切换数据源=================");
Class<?> target = point.getTarget().getClass();
MethodSignature signature = (MethodSignature) point.getSignature();
// 默认使用目标类型的注解,如果没有则使用其实现接口的注解
for (Class<?> clazz : target.getInterfaces()) {
resolveDataSource(clazz, signature.getMethod());
}
resolveDataSource(target, signature.getMethod());
}
/**
* 提取目标对象方法注解和类型注解中的数据源标识
*
* @param clazz
* @param method
*/
private void resolveDataSource(Class<?> clazz, Method method) {
try {
Class<?>[] types = method.getParameterTypes();
// 默认使用类型注解
if (clazz.isAnnotationPresent(DataSource.class)) {
DataSource source = clazz.getAnnotation(DataSource.class);
DynamicDataSourceHolder.setDataSource(source.value());
}
// 方法注解可以覆盖类型注解
Method m = clazz.getMethod(method.getName(), types);
if (m != null && m.isAnnotationPresent(DataSource.class)) {
DataSource source = m.getAnnotation(DataSource.class);
DynamicDataSourceHolder.setDataSource(source.value());
}
} catch (Exception e) {
System.out.println(clazz + ":" + e.getMessage());
}
}
/**
* @param
* @return void 方法调用完毕后,清除缓存的数据源,不然在多线程的切换中会报错,导致另一个数据源的数据使用了前一个数据源的数据
*/
@SuppressWarnings("unused")
private void clearDataSource() {
System.out.println("=================清除缓存==============");
DynamicDataSourceHolder.clearDataSource();
}
}
使用
在service层增加注解来切换数据源,spring-content.xml中有配置 所扫描的包要和配置中的一致