Spring AOP 實現讀寫分離
阿新 • • 發佈:2018-03-13
靈活 結果 only method 行為 execution adl 數據源 tps
原文地址:Spring AOP 實現讀寫分離
博客地址:http://www.extlight.com
一、前言
上一篇《MySQL 實現主從復制》 文章中介紹了 MySQL 主從復制的搭建,為了在項目上契合數據庫的主從架構,本篇將介紹在應用層實現對數據庫的讀寫分離。
二、原理
配置主從數據源,當接收請求時,執行具體方法之前(攔截),判斷請求具體操作(讀或寫),最終確定從哪個數據源獲取連接訪問數據庫。
在 JavaWeb 開發中,有 3 種方式可以對請求進行攔截:
filter:攔截所有請求
intercetor:攔截 handler/Action
aop 切面:依賴切入點
不難看出,使用 AOP 切面進行攔截最合理和靈活,因此本文將介紹使用 AOP 實現讀寫分離功能。
三、編碼
本文只張貼關鍵性代碼,詳細代碼請下載文章末尾源碼進行查看。
3.1 代碼
1)DynamicDataSourceHolder 確保線程安全:
/**
*
* 使用ThreadLocal技術來記錄當前線程中的數據源的key
*
*/
public class DynamicDataSourceHolder {
//寫庫對應的數據源key
private static final String MASTER = "master";
//讀庫對應的數據源key
private static final String SLAVE = "slave" ;
//使用ThreadLocal記錄當前線程的數據源key
private static final ThreadLocal<String> holder = new ThreadLocal<String>();
/**
* 設置數據源key
* @param key
*/
public static void putDataSourceKey(String key) {
holder.set(key);
}
/**
* 獲取數據源key
* @return
*/
public static String getDataSourceKey() {
return holder.get();
}
/**
* 標記寫庫
*/
public static void markMaster(){
putDataSourceKey(MASTER);
}
/**
* 標記讀庫
*/
public static void markSlave(){
putDataSourceKey(SLAVE);
}
}
2)定義 AOP 切面判斷當前線程的讀寫操作
/**
* 定義數據源的AOP切面,通過該Service的方法名判斷是應該走讀庫還是寫庫
*
*/
public class DataSourceAspect {
/**
* 在進入Service方法之前執行
*
* @param point 切面對象
*/
public void before(JoinPoint point) {
// 獲取到當前執行的方法名
String methodName = point.getSignature().getName();
if (isSlave(methodName)) {
// 標記為讀庫
DynamicDataSourceHolder.markSlave();
} else {
// 標記為寫庫
DynamicDataSourceHolder.markMaster();
}
}
/**
* 判斷是否為讀庫
*
* @param methodName
* @return
*/
private Boolean isSlave(String methodName) {
// 方法名以query、find、get開頭的方法名走從庫
return StringUtils.startsWithAny(methodName, "query", "find", "get");
}
}
3)定義動態數據源,確定最終使用的數據源:
/**
* 定義動態數據源,實現通過集成Spring提供的AbstractRoutingDataSource,只需要實現determineCurrentLookupKey方法即可
*
* 由於DynamicDataSource是單例的,線程不安全的,所以采用ThreadLocal保證線程安全,由DynamicDataSourceHolder完成。
*
*/
public class DynamicDataSource extends AbstractRoutingDataSource{
@Override
protected Object determineCurrentLookupKey() {
// 使用DynamicDataSourceHolder保證線程安全,並且得到當前線程中的數據源key
String dataSourceKey = DynamicDataSourceHolder.getDataSourceKey();
System.out.println("dataSourceKey ======> "+dataSourceKey);
return dataSourceKey;
}
}
3.2 配置文件
1)jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.master.url=jdbc:mysql://192.168.2.21/mysql_test?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=UTC
jdbc.master.username=root
jdbc.master.password=tiger
jdbc.slave01.url=jdbc:mysql://192.168.2.22/mysql_test?characterEncoding=utf-8&allowMultiQueries=true&serverTimezone=UTC
jdbc.slave01.username=root
jdbc.slave01.password=tiger
2)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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<context:component-scan base-package="com.light.*">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:property-placeholder location="classpath:*.properties"/>
<!-- 數據源 -->
<bean id="dataSource" class="com.light.dynamicdatasource.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="master" value-ref="masterDataSource"></entry>
<entry key="slave" value-ref="slave01DataSource"></entry>
</map>
</property>
<!-- 默認數據源 -->
<property name="defaultTargetDataSource" ref="masterDataSource"/>
</bean>
<!-- 主庫數據源 -->
<bean id="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="${jdbc.master.url}"/>
<property name="username" value="${jdbc.master.username}"/>
<property name="password" value="${jdbc.master.password}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="initialSize" value="5"/>
<property name="minIdle" value="5"/>
<property name="maxActive" value="50"/>
</bean>
<!-- 從庫數據源 -->
<bean id="slave01DataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="${jdbc.slave01.url}"/>
<property name="username" value="${jdbc.slave01.username}"/>
<property name="password" value="${jdbc.slave01.password}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="initialSize" value="5"/>
<property name="minIdle" value="5"/>
<property name="maxActive" value="50"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 引入 mybatis 配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
<property name="typeAliasesPackage" value="com.light.domain"></property>
<!-- sql配置文件 -->
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"></property>
</bean>
<!-- 掃描Mapper -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.light.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 傳播行為 -->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<bean id="dataSourceAspect" class="com.light.dynamicdatasource.DataSourceAspect"></bean>
<aop:config proxy-target-class="true">
<aop:pointcut id="myPointcut" expression="execution(* com.light.service.*.*(..))" />
<!-- 事務切面 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/>
<!-- 自定義切面 -->
<aop:aspect ref="dataSourceAspect" order="-9999">
<aop:before method="before" pointcut-ref="myPointcut" />
</aop:aspect>
</aop:config>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
四、測試
筆者在項目的 web 層寫了 UserController 類,裏邊包含 get 和 delete 兩個方法。
正常情況,當訪問 get 方法(讀操作)時,使用從庫數據源,那麽控制臺應該打印 slave 。
正常情況,當訪問 delete 方法(寫操作)時,使用主庫數據源,那麽控制臺應該打印 master 。
以下是 2 次測試結果:
get 方法:
delete 方法:
五、源碼
源碼下載
Spring AOP 實現讀寫分離