利用AbstractRoutingDataSource+AOP實現多資料來源切換
阿新 • • 發佈:2019-02-09
實現功能
實現基於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庫為空,最後測試效果如下: