版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fzuzhanghao1993/article/details/80107960
实现功能
实现基于springmvc+mybatis框架动态切换不同的数据源。
基础框架springmvc4+mybatis3
实现原理
主要利用了spring aop以及spring的AbstractRoutingDataSource类。
AbstractRoutingDataSource
通过观察源码,可以抽取该类中几个重要元素
properties:
private Map<Object, Object> targetDataSources;
private Object defaultTargetDataSource;
functions:
@Override
public void afterPropertiesSet() {
if (this.targetDataSources == null) {
throw new IllegalArgumentException("Property 'targetDataSources' is required");
}
this.resolvedDataSources = new HashMap<Object, DataSource>(this.targetDataSources.size());
for (Map.Entry<Object, Object> entry : this.targetDataSources.entrySet()) {
Object lookupKey = resolveSpecifiedLookupKey(entry.getKey());
DataSource dataSource = resolveSpecifiedDataSource(entry.getValue());
this.resolvedDataSources.put(lookupKey, dataSource);
}
if (this.defaultTargetDataSource != null) {
this.resolvedDefaultDataSource = resolveSpecifiedDataSource(this.defaultTargetDataSource);
}
}
public Connec
tion getConnection() throws SQLException {
return determineTargetDataSource().getConnection();
}
protected DataSource determineTargetDataSource() {
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = determineCurrentLookupKey();
DataSource dataSource = this.resolvedDataSources.get(lookupKey);
if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
dataSource = this.resolvedDefaultDataSource;
}
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
}
return dataSource;
}
通过解读源码,可以知道,targetDataSources用来初始化预存的数据源,defaultTargetDataSource则是默认数据源,当determineTargetDataSource获取不到用户定义的数据源时,使用该默认数据源。在determineTargetDataSource中通过determineCurrentLookupKey来获取自定义数据源的KEY,这也正是我们要复写的方法。
如果每次方法调用都去手动切换数据源,一方面代码耦合度高,另一方面可维护性可扩展性差,因此我们利用spring aop编写pointcut去执行动态切换。
具体配置
spring配置文件(部分)
<!-- 主数据源 1-->
<bean id="mysqlDataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.master.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.master.url}" />
<property name="user" value="${jdbc.master.username}" />
<property name="password" value="${jdbc.master.password}" />
<property name="initialPoolSize" value="${jdbc.master.c3p0.initialPoolSize}" />
<property name="minPoolSize" value="${jdbc.master.c3p0.min_size}" />
<property name="maxPoolSize" value="${jdbc.master.c3p0.max_size}" />
<property name="maxIdleTime" value="${jdbc.master.c3p0.max_idle_time}" />
<property name="acquireIncrement" value="${jdbc.master.c3p0.acquire_increment}" />
<property name="maxStatements" value="${jdbc.master.c3p0.max_statements}" />
<property name="idleConnectionTestPeriod" value="${jdbc.master.c3p0.idle_connection_test_period}" />
<property name="checkoutTimeout" value="${jdbc.master.c3p0.checkout_timeout}" />
<property name="testConnectionOnCheckin" value="${jdbc.master.c3p0.test_connection_on_checkin}" />
<property name="automaticTestTable" value="${jdbc.master.c3p0.automatic_test_table}" />
<property name="preferredTestQuery" value="${jdbc.master.c3p0.preferred_test_query}" />
</bean>
<!-- 从数据源 2-->
<bean id="mysqlDataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.slave.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.slave.url}" />
<property name="user" value="${jdbc.slave.username}" />
<property name="password" value="${jdbc.slave.password}" />
<property name="initialPoolSize" value="${jdbc.slave.c3p0.initialPoolSize}" />
<property name="minPoolSize" value="${jdbc.slave.c3p0.min_size}" />
<property name="maxPoolSize" value="${jdbc.slave.c3p0.max_size}" />
<property name="maxIdleTime" value="${jdbc.slave.c3p0.max_idle_time}" />
<property name="acquireIncrement" value="${jdbc.slave.c3p0.acquire_increment}" />
<property name="maxStatements" value="${jdbc.slave.c3p0.max_statements}" />
<property name="idleConnectionTestPeriod" value="${jdbc.slave.c3p0.idle_connection_test_period}" />
<property name="checkoutTimeout" value="${jdbc.slave.c3p0.checkout_timeout}" />
<property name="testConnectionOnCheckin" value="${jdbc.slave.c3p0.test_connection_on_checkin}" />
<property name="automaticTestTable" value="${jdbc.slave.c3p0.automatic_test_table}" />
<property name="preferredTestQuery" value="${jdbc.slave.c3p0.preferred_test_query}" />
</bean>
<!-- 多数据源配置 -->
<bean id="dataSource" class="com.test.tools.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry value-ref="mysqlDataSource1" key="mysqlDataSource1"></entry>
<entry value-ref="mysqlDataSource2" key="mysqlDataSource2"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="mysqlDataSource1"></property>
</bean>
<!-- sessionfactory1 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" lazy-init="false" >
<property name="configLocation" value="classpath:/mybatis/mybatis-config.xml" />
<property name="mapperLocations" value="classpath*:/mybatis/mappers/*.xml" />
<property name="dataSource" ref="dataSource" />
</bean>
<bean name="mapperConf" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="annotationClass" value="org.springframework.stereotype.Repository" />
<property name="basePackage" value="com.**.dao" />
</bean>
......
<!--使用aspectj创建aop -->
<aop:aspectj-autoproxy/>
<bean id="dataSourceAspect" class="com.test.aspect.DataSourceAspect"></bean>
......
jdbc配置文件如下
jdbc.master.driverClassName=com.mysql.jdbc.Driver
jdbc.master.url=jdbc:mysql://127.0.0.1:3360/test2?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
jdbc.master.username=root
jdbc.master.password=Landi12345
jdbc.master.c3p0.acquire_increment=2
jdbc.master.c3p0.initialPoolSize=2
jdbc.master.c3p0.min_size=2
jdbc.master.c3p0.max_size=10
jdbc.master.c3p0.max_idle_time=180
jdbc.master.c3p0.max_statements=0
jdbc.master.c3p0.idle_connection_test_period=180
jdbc.master.c3p0.checkout_timeout=30000
jdbc.master.c3p0.test_connection_on_checkin=true
jdbc.master.c3p0.automatic_test_table=c3p0_test
jdbc.master.c3p0.preferred_test_query=select * from "c3p0_test"
jdbc.slave.driverClassName=com.mysql.jdbc.Driver
jdbc.slave.url=jdbc:mysql://127.0.0.1:3306/test2?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
jdbc.slave.username=root
jdbc.slave.password=Landi123456
jdbc.slave.c3p0.acquire_increment=2
jdbc.slave.c3p0.initialPoolSize=2
jdbc.slave.c3p0.min_size=2
jdbc.slave.c3p0.max_size=10
jdbc.slave.c3p0.max_idle_time=180
jdbc.slave.c3p0.max_statements=0
jdbc.slave.c3p0.idle_connection_test_period=180
jdbc.slave.c3p0.checkout_timeout=30000
jdbc.slave.c3p0.test_connection_on_checkin=true
jdbc.slave.c3p0.automatic_test_table=c3p0_test
jdbc.slave.c3p0.preferred_test_query=select * from "c3p0_test"
jdbc.transation_timeout=1800
自定义注解类DataSource
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {
String value();
}
数据源控制类DynamicDataSource、DynamicDataSourceHolder
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDataSourceType();
}
}
public class DynamicDataSourceHolder {
// 线程局部变量(多线程并发设计,为了线程安全)
private static final ThreadLocal<String> contextHolder = new ThreadLocal();
// 设置数据源类型
public static void setDataSourceType(String dataSourceType) {
contextHolder.set(dataSourceType);
}
// 获取数据源类型
public static String getDataSourceType() {
return (String) contextHolder.get();
}
// 清除数据源类型
public static void clearDataSourceType() {
contextHolder.remove();
}
}
切面类DataSourceAspect ,用于控制切换,切入点为service
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import com.test.tools.DynamicDataSourceHolder;
import com.test.utils.DataSource;
@Aspect
public class DataSourceAspect {
private final static Logger log = Logger.getLogger(DataSourceAspect.class);
@Before("execution(* com.test.service..*.*(..))&&@annotation(ds)")
public void changeDataSource(JoinPoint point, DataSource ds) throws Throwable {
String key = ds.value();
if(key!=null && !key.trim().equals("")){
DynamicDataSourceHolder.setDataSourceType(key);
}
}
@After("execution(* com.test.service..*.*(..))&&@annotation(ds)")
public void restoreDataSource(JoinPoint point, DataSource ds) {
DynamicDataSourceHolder.clearDataSourceType();
}
}
测试用的service,用于查询权限
编写一个测试用例
/**
*
* <br>
* <b>功能:</b>SysAuthoService<br>
*/
@Service("sysauthoService")
public class SysAuthoServiceImpl extends BaseServiceImpl implements SysAuthoService {
private final static Logger log= Logger.getLogger(SysAuthoServiceImpl.class);
@Resource
private SysAuthoDao dao;
public SysAuthoDao getDao() {
return dao;
}
@DataSource(value="mysqlDataSource1")
@Override
public List<ListBean> readWebList(SysAutho queryObj) {
return dao.readWebList(queryObj);
}
@DataSource(value="mysqlDataSource2")
@Override
public List<ListBean> readWebList2(SysAutho queryObj) {
return dao.readWebList2(queryObj);
}
}
这里controller和mybatis的配置代码就不给出了,具体业务系统自己编写,测试数据中1库有数据,2库为空,最后测试效果如下: