SSM项目使用AOP实现简单的读写分离

18 篇文章 0 订阅
4 篇文章 0 订阅

准备条件

事先准备两个数据库服务,并配置为主从分布(master-slave),主机服务用于写,从机服务只用来读。具体配置请前往https://blog.csdn.net/guandongsheng110/article/details/71173080查看。

1. pom.xml添加jar

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.2</version>
</dependency>

2. 添加数据源配置类

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<>();

    public static void putDataSourceKey(String key) {
        holder.set(key);
    }

    public static String getDataSourceKey() {
        return holder.get();
    }

    public static void markMaster(){
        putDataSourceKey(MASTER);
    }

    public static void markSlave(){
        putDataSourceKey(SLAVE);
    }
}

3. 添加自定义数据源类

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * Created by GuanDS on 2019/1/24.
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        // 由于DynamicDataSource是单例的,线程不安全的,所以采用ThreadLocal保证线程安全
        // 由DynamicDataSourceHolder完成
        return DynamicDataSourceHolder.getDataSourceKey();
    }
}

4. 添加切面类(根据方法名匹配选择主或从数据库)

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;

/**
 * Created by GuanDS on 2019/1/24.
 */
public class DataSourceAspect {

    public void before(JoinPoint point) {
        // 获取到当前执行的方法名
        String methodName = point.getSignature().getName();
        if (isSlave(methodName)) {
            // 标记为读库
            DynamicDataSourceHolder.markSlave();
        } else {
            // 标记为写库
            DynamicDataSourceHolder.markMaster();
        }
    }

    private Boolean isSlave(String methodName) {
        // 方法名以query、find、get开头的方法名走从库
        return StringUtils.startsWithAny(methodName, "query", "find", "get");
    }
}

5. 配置xml文件

<bean id="baseDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="poolPreparedStatements" value="true"/>
    <property name="initialSize" value="10"/>
    <property name="maxActive" value="100"/>
    <property name="maxIdle" value="5"/>
    <property name="testOnBorrow" value="true"/>
    <property name="testWhileIdle" value="true"/>
</bean>

<bean id="masterDataSource" parent="baseDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="${db.url}"/>
    <property name="username" value="${db.user}"/>
    <property name="password" value="${db.password}"/>
    <property name="validationQuery" value="select 1"/>
</bean>

<bean id="slaveDataSource" parent="baseDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="${rdb.url}"/>
    <property name="username" value="${rdb.user}"/>
    <property name="password" value="${rdb.password}"/>
    <property name="validationQuery" value="select 1"/>
</bean>

<bean id="dataSource" class="cn.guanyibei.commons.datasource.DynamicDataSource">
    <!-- 设置多个数据源 -->
    <property name="targetDataSources">
        <map key-type="java.lang.String">
            <entry key="master" value-ref="masterDataSource"/>
            <entry key="slave" value-ref="slaveDataSource"/>
        </map>
    </property>
    <property name="defaultTargetDataSource" ref="masterDataSource"/>
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mapperLocations">
        <list>
            <value>classpath:cn/guanyibei/commons/mapper/*.xml</value>
        </list>
    </property>
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.guanyibei.commons.mapper"/>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>


<!-- 定义AOP切面处理器 -->
<bean class="cn.guanyibei.commons.datasource.DataSourceAspect" id="dataSourceAspect"/>
<aop:config>
    <!-- 定义切面,所有的service的所有方法 -->
    <aop:pointcut id="txPointcut" expression="execution(* cn.guanyibei.commons.service.*.*(..))"/>
    <!-- 应用事务策略到Service切面 -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    <!-- 将切面应用到自定义的切面处理器上,-9999保证该切面优先级最高执行 -->
    <aop:aspect ref="dataSourceAspect" order="-9999">
        <aop:before method="before" pointcut-ref="txPointcut"/>
    </aop:aspect>
</aop:config>

<!-- 定义事务管理器 -->
<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="query*" read-only="true"/>
        <tx:method name="find*" read-only="true"/>
        <tx:method name="get*" read-only="true"/>

        <!-- 主库执行操作,事务传播行为定义为默认行为 -->
        <tx:method name="save*" propagation="REQUIRED"/>
        <tx:method name="update*" propagation="REQUIRED"/>
        <tx:method name="delete*" propagation="REQUIRED"/>

        <!--其他方法使用默认事务策略 -->
        <tx:method name="*"/>
    </tx:attributes>
</tx:advice>

6. 测试成功

 

增强配置

1. 配置spring.xml文件

<!-- 定义AOP切面处理器 -->
<bean class="cn.guanyibei.commons.datasource.DataSourceAspect" id="dataSourceAspect">
    <!-- 指定事务策略 -->
    <property name="txAdvice" ref="txAdvice"/>
</bean>

2. 编辑Aspect.java(先根据事务配置选择数据库,如果没有配置,再根据方法名选择数据库

public class DataSourceAspect {
    private List<String> slaveMethodPattern = new ArrayList<>();

    @SuppressWarnings("unchecked")
    public void setTxAdvice(TransactionInterceptor txAdvice) throws Exception {
        if (txAdvice == null) { // 没有配置事务管理策略
            return;
        }
        //从txAdvice获取到策略配置信息
        TransactionAttributeSource transactionAttributeSource = txAdvice.getTransactionAttributeSource();
        if (!(transactionAttributeSource instanceof NameMatchTransactionAttributeSource)) {
            return;
        }
        //使用反射技术获取到NameMatchTransactionAttributeSource对象中的nameMap属性值
        NameMatchTransactionAttributeSource matchTransactionAttributeSource = (NameMatchTransactionAttributeSource) transactionAttributeSource;
        Field nameMapField = ReflectionUtils.findField(NameMatchTransactionAttributeSource.class, "nameMap");
        nameMapField.setAccessible(true); //设置该字段可访问
        //获取nameMap的值
        Map<String, TransactionAttribute> map = (Map<String, TransactionAttribute>) nameMapField.get(matchTransactionAttributeSource);
        //遍历nameMap
        for (Map.Entry<String, TransactionAttribute> entry : map.entrySet()) {
            if (!entry.getValue().isReadOnly()) {//判断之后定义了ReadOnly的策略才加入到slaveMethodPattern
                continue;
            }
            slaveMethodPattern.add(entry.getKey());
        }
    }

    public void before(JoinPoint point) {
        // 获取到当前执行的方法名
        String methodName = point.getSignature().getName();
        boolean isSlave = false;
        if (slaveMethodPattern.isEmpty()) {
            isSlave = StringUtils.startsWithAny(methodName, "query", "find", "get");
        } else { // 使用策略规则匹配
            for (String mappedName : slaveMethodPattern) {
                if (PatternMatchUtils.simpleMatch(methodName, mappedName)) {
                    isSlave = true;
                    break;
                }
            }
        }
        if (isSlave) {
            DynamicDataSourceHolder.markSlave();
        } else {
            DynamicDataSourceHolder.markMaster();
        }
    }

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值