1. 程式人生 > >Spring + Mybatis環境實現Mysql資料庫主從切換

Spring + Mybatis環境實現Mysql資料庫主從切換

一、簡述:

資料庫應用場景中,經常是“讀多寫少”,也就是對資料庫讀取資料壓力比較大。有一個解決方案是採用資料庫叢集方案。
一個數據庫是主庫,負責寫;其他為從庫,負責讀。實現:讀寫分離。
那麼,對我們的要求是:
1. 讀庫和寫庫的資料一致;
2. 寫資料必須寫到寫庫;
3. 讀資料必須到讀庫;

二、方案:

實現讀寫分離有兩種方案:應用層解決和中介軟體解決;
本篇,介紹使用Spring方式,實現應用層解決方式。

三、原理:

在進入Service之前,使用AOP來做出判斷,是使用寫庫還是讀庫,判斷依據可以根據方法名判斷,比如說以query、find、get等開頭的就走讀庫,其他的走寫庫

說明:也可使用mybatis外掛方式,通過判斷語句INSERT,UPDATE,DELETE,SELECT判斷;(推薦)

image
image

四、實際解決方案:

  • 方案一:Spring AOP註解方式;
  • 方案二:Spring AOP介面方法名限定方式;
  • 方案三:Mybatis 外掛判斷SQL語句方式;(推薦)
以下使用方案三:

參與角色:

1、RouteDataSourceKeyEnum 主從資料庫列舉

2、RouteDataSource 動態切換資料來源

3、RouteDataSourcePlugin MyBtais攔截外掛

4、spring-mybatis.xml 資料來源,切換類配置檔案

程式碼:

1、RouteDataSourceKeyEnum.java檔案:

/**
 * @author devin
 * @date 2017/11/1
 */
public enum RouteDataSourceKeyEnum {
    MASTER, SLAVE
}

2、RouteDataSource.java檔案:

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

/**
 * @author devin
 * @date 2017/10/23
 */
public class
RouteDataSource extends AbstractRoutingDataSource {
/** * dbKey執行緒安全容器 */ private static ThreadLocal<String> holder = new ThreadLocal<>(); @Override protected Object determineCurrentLookupKey() { return holder.get(); } /** * 設定dbKey * * @param dbKey */ public static void setDbKey(RouteDataSourceKeyEnum dbKey) { holder.set(dbKey.name()); } }

3、RouteDataSourcePlugin.java檔案:

import com.framework.datasource.DynamicDataSourceGlobal;
import com.framework.datasource.DynamicDataSourceHolder;
import com.framework.util.GlobalKeys;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.keygen.SelectKeyGenerator;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author devin
 * @date 2017/10/23
 * 在DefaultSqlSession的insert,delete方法也是呼叫了update方法
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {
                MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {
                MappedStatement.class, Object.class, RowBounds.class,
                ResultHandler.class})})
public class RouteDataSourcePlugin implements Interceptor {
    protected static final Logger logger = LoggerFactory.getLogger(RouteDataSourcePlugin.class);

    private static final String REGEX = ".*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*";

    private static final Map<String, RouteDataSourceKeyEnum> cacheMap = new ConcurrentHashMap<>();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //常量切換 生產 測試庫
        boolean gamma = Boolean.parseBoolean(GlobalKeys.getString("db.source.switch"));
        if (gamma) {
            RouteDataSource.setDbKey(RouteDataSourceKeyEnum.MASTER);
            return invocation.proceed();
        } else if (!gamma) {
            RouteDataSource.setDbKey(RouteDataSourceKeyEnum.SLAVE);
            return invocation.proceed();
        }
        //它首先檢視當前是否存在事務管理上下文,並嘗試從事務管理上下文獲取連線,如果獲取失敗,直接從資料來源中獲取連線。
        //在獲取連線後,如果當前擁有事務上下文,則將連線繫結到事務上下文中。(此處直接繼續下一過程)
        boolean synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();
        if (!synchronizationActive) {
            Object[] objects = invocation.getArgs();
            MappedStatement ms = (MappedStatement) objects[0];

            RouteDataSourceKeyEnum routeDataSourceKeyEnum = null;

            if ((routeDataSourceKeyEnum = cacheMap.get(ms.getId())) == null) {
                //讀方法
                if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
                    //!selectKey 為自增id查詢主鍵(SELECT LAST_INSERT_ID() )方法,使用主庫
                    if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
                        routeDataSourceKeyEnum = RouteDataSourceKeyEnum.MASTER;
                    } else {
                        BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
                        String sql = boundSql.getSql().toLowerCase(Locale.CHINA).replaceAll("[\\t\\n\\r]", " ");
                        if (sql.matches(REGEX)) {
                            routeDataSourceKeyEnum = RouteDataSourceKeyEnum.MASTER;
                        } else {
                            routeDataSourceKeyEnum = RouteDataSourceKeyEnum.SLAVE;
                        }
                    }
                } else {
                    routeDataSourceKeyEnum = RouteDataSourceKeyEnum.MASTER;
                }
                logger.warn("設定方法[{}] use [{}] Strategy, SqlCommandType [{}]..", ms.getId(), routeDataSourceKeyEnum.name(), ms.getSqlCommandType().name());
                cacheMap.put(ms.getId(), routeDataSourceKeyEnum);
            }
            RouteDataSource.setDbKey(routeDataSourceKeyEnum);
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {
        //
    }
}

4、spring-mybatis.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

    <!-- 引入配置檔案 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"/>
    </bean>

    <bean id="masterDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
        <!-- 初始化連線大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 連線池最大數量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 連線池最大空閒 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 連線池最小空閒 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 獲取連線最大等待時間 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <bean id="slaveDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url_slave}"/>
        <property name="username" value="${username_slave}"/>
        <property name="password" value="${password_slave}"/>
        <!-- 初始化連線大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 連線池最大數量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 連線池最大空閒 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 連線池最小空閒 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 獲取連線最大等待時間 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <!--動態獲取資料庫-->
    <bean id="dataSource" class="com.framework.routedb.RouteDataSource">
        <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"></property>
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 自動掃描mapping.xml檔案 -->
        <property name="mapperLocations" value="classpath:mapper/**/*.xml"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="plugins">
            <list>
                <bean class="com.huxin.assets.framework.routedb.RouteDataSourcePlugin"></bean>
            </list>
        </property>
    </bean>

    <!-- DAO介面所在包名,Spring會自動查詢其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.**.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

參考資料: