Spring+Mybatis实现主从数据库读写分离

Spring+Mybatis实现主从数据库读写分离

采用配置+注解的方式。

自定义@DataSource注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE, ElementType.METHOD})
public @interface DataSource {
    String value();
}

实现抽象DataSource

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

public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceHandler.getDataSourceType();
    }
}

数据源控制类

public class DataSourceHandler {
    /**
     * 线程本地环境
     */
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    /**
     * 设置数据源类型
     * @param dataSourceType
     */
    public static void setDataSourceType(String dataSourceType) {
        contextHolder.set(dataSourceType);
    }

    /**
     * 获取数据源类型
     * @return
     */
    public static String getDataSourceType() {
        return (String) contextHolder.get();
    }

    /**
     * 清除数据源类型
     */
    public static void clearDataSourceType() {
        contextHolder.remove();
    }
}

利用AOP切面编程,在Service事务开始之前选择数据源

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class DataSourceExchange implements MethodBeforeAdvice, AfterReturningAdvice {
    @Override
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        DataSourceHandler.clearDataSourceType();
    }

    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        if (method.getDeclaringClass().isAnnotationPresent(DataSource.class)) {
            DataSource dataSource = method.getDeclaringClass().getAnnotation(DataSource.class);
            DataSourceHandler.setDataSourceType(dataSource.value());
        } else if (method.isAnnotationPresent(DataSource.class)) {
            DataSource dataSource = method.getAnnotation(DataSource.class);
            DataSourceHandler.setDataSourceType(dataSource.value());
        } else {
            DataSourceHandler.setDataSourceType("read");
        }
    }
}

applicationContext-source.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
    <!-- 数据源基本配置 -->
    <bean name="basicDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本属性 url、user、password -->
        <property name="url" value="${datasource.url}" />
        <property name="username" value="${datasource.username}" />
        <property name="password" value="${datasource.password}" />
        <property name="driverClassName" value="${driverClassName}" />
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${initialSize}" />
        <!-- 最小空闲连接数 -->
        <property name="minIdle" value="${minIdle}" />
        <!-- 最大并发连接数 -->
        <property name="maxActive" value="${maxActive}" />
        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="${maxWait}" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
        <property name="validationQuery" value="${validationQuery}" />
        <property name="testWhileIdle" value="${testWhileIdle}" />
        <property name="testOnBorrow" value="${testOnBorrow}" />
        <property name="testOnReturn" value="${testOnReturn}" />
        <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
        <!-- 打开 removeAbandoned 功能 -->
        <property name="removeAbandoned" value="${removeAbandoned}" />
        <!-- 1800 秒,也就是 30 分钟 -->
        <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />

        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 mysql false -->
        <property name="poolPreparedStatements" value="false" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
        <!-- 配置监控统计拦截的filters -->
        <!--<property name="filters" value="config,stat,log4j,wall" />-->
        <property name="filters" value="${filters}" />
        <property name="connectionProperties" value="config.decrypt=false" />
        <!-- 关闭 abanded 连接时输出错误日志 -->
        <property name="logAbandoned" value="${logAbandoned}" />
    </bean>
    <!-- 配置 写 数据源 -->
    <bean name="writeDataSource" parent="basicDataSource">
        <!-- 基本属性 url、user、password -->
        <property name="url" value="${writeDataSourceUrl}" />
        <property name="password" value="${writeDataSourcePassword}" />
    </bean>
    <!-- 配置 读 数据源 -->
    <bean name="readDataSource" parent="basicDataSource">
        <!-- 基本属性 url、user、password -->
        <property name="url" value="${datasource.url}" />
        <property name="password" value="${datasource.password}" />
    </bean>
    <!-- dataSource抽象类 -->
    <bean id="dataSource" class="com.demo.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry value-ref="readDataSource" key="read" />
                <entry value-ref="writeDataSource" key="write" />
            </map>
        </property>
        <property name="defaultTargetDataSource" ref="writeDataSource" />
    </bean>

    <bean id="dataSourceExchange" class="com.demo.DataSourceExchange" />

    <!--mybatis sqlSessionFactory session 工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--
            自动扫描mapping.xml文件 mapperLocations 属性使用一个资源位置的 list。 这个属性可以用来指定
            MyBatis 的 XML 映射器文件的位置。 它的值可以包含 Ant 样式来加载一个目录中所有文件, 或者从基路径下 递归搜索所有路径-->
        <property name="mapperLocations" >
            <array>
                <value>classpath:com/mybatis/mapping/*.xml</value>
            </array>
        </property>
        <!-- mybatis-config.xml留着还可以配置其他的东西 -->
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
    </bean>
    <!--创建数据映射器,数据映射器必须为接口 mybatis-spring 自动扫描dao -->
    <!-- 通过扫描包,自动配置包下的代理 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.demo.dao" />
    </bean>
    <!-- jdbc事务管理器 -->
    <bean id="transactionManager"
              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!--事务模板 -->
    <bean id="transactionTemplate"
            class="org.springframework.transaction.support.TransactionTemplate">
            <property name="transactionManager" ref="transactionManager" />
    </bean> 
    <!--配置通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" />
            <tx:method name="exist*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="query*" read-only="true" />
            <tx:method name="list*" read-only="true" />
            
            <!-- 在update开头的方法中遇到异常(Throwable)就回滚-->
            <tx:method name="update*" rollback-for="Throwable"/>
            <tx:method name="del*"  rollback-for="Throwable" />
            <tx:method name="delete*"  rollback-for="Throwable" />
            <tx:method name="last*"  rollback-for="Throwable" />
            
            <tx:method name="queryAndUpdate*" propagation="REQUIRED" rollback-for="Exception" />
            <tx:method name="remove*" propagation="REQUIRED" rollback-for="Exception" />
            <tx:method name="save*" propagation="REQUIRED" rollback-for="Exception" />
            <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />
            <tx:method name="create*" propagation="REQUIRED" rollback-for="Exception" />
        </tx:attributes>
    </tx:advice>
    <tx:annotation-driven transaction-manager="transactionManager" />
    <!--切面,针对于复杂业务放到service层处理,这样可以进行回滚操作-->
    <aop:config>
        <aop:pointcut expression="execution(public * com.*.service.*.*(..))" id="bussinessService" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService" order="2" />
        <aop:advisor advice-ref="dataSourceExchange" pointcut-ref="bussinessService" order="1" />
    </aop:config>

    
    <!-- 创建一个sqlSession实例,线程安全的,可以在所有DAO实例共享,原理是将sqlSession,事务与当前线程挂钩 -->
    <bean name="sqlSessionTemplate" id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>
</beans>

动态选择数据源

在Service类或方法前添加@DataSource("read")@DataSource("write")即可,默认使用read源。

猜你喜欢

转载自www.cnblogs.com/cncul/p/11721028.html