天天看點

【Spring】如何實作多資料源讀寫分離?這是我看過最詳細的一篇!!

背景

我們一般應用對資料庫而言都是“讀多寫少”,也就說對資料庫讀取資料的壓力比較大,有一個思路就是說采用資料庫叢集的方案,

其中一個是主庫,負責寫入資料,我們稱之為:寫庫;其它都是從庫,負責讀取資料,我們稱之為:讀庫;

那麼,對我們的要求是:

  • 讀庫和寫庫的資料一緻;
  • 寫資料必須寫到寫庫;
  • 讀資料必須到讀庫;

方案

解決讀寫分離的方案有兩種:應用層解決和中間件解決。

應用層解決

【Spring】如何實作多資料源讀寫分離?這是我看過最詳細的一篇!!

優點:

  • 多資料源切換友善,由程式自動完成;
  • 不需要引入中間件;
  • 理論上支援任何資料庫;

缺點:

  • 由程式員完成,運維參與不到;
  • 不能做到動态增加資料源;

中間件解決

【Spring】如何實作多資料源讀寫分離?這是我看過最詳細的一篇!!
  • 源程式不需要做任何改動就可以實作讀寫分離;
  • 動态添加資料源不需要重新開機程式;
  • 程式依賴于中間件,會導緻切換資料庫變得困難;
  • 由中間件做了中轉代理,性能有所下降;

Spring方案

原理

【Spring】如何實作多資料源讀寫分離?這是我看過最詳細的一篇!!

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

DynamicDataSource

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
 
/**
 * 定義動态資料源,實作通過內建Spring提供的AbstractRoutingDataSource,隻需要實作determineCurrentLookupKey方法即可
 * 由于DynamicDataSource是單例的,線程不安全的,是以采用ThreadLocal保證線程安全,由DynamicDataSourceHolder完成。
 * @author binghe
 */
public class DynamicDataSource extends AbstractRoutingDataSource{
 
    @Override
    protected Object determineCurrentLookupKey() {
        // 使用DynamicDataSourceHolder保證線程安全,并且得到目前線程中的資料源key
        return DynamicDataSourceHolder.getDataSourceKey();
    }
 
}      

DynamicDataSourceHolder

/**
 * 使用ThreadLocal技術來記錄目前線程中的資料源的key
 * @author binghe
 */
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);
    }
 
}      

DataSourceAspect

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
 
/**
 * 定義資料源的AOP切面,通過該Service的方法名判斷是應該走讀庫還是寫庫
 * @author binghe
 */
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");
    }
 
}      

配置2個資料源

jdbc.properties

jdbc.master.driver=com.mysql.jdbc.Driver
jdbc.master.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
jdbc.master.username=root
jdbc.master.password=123456
jdbc.slave01.driver=com.mysql.jdbc.Driver
jdbc.slave01.url=jdbc:mysql://127.0.0.1:3307/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
jdbc.slave01.username=root
jdbc.slave01.password=123456      

定義連接配接池

<!-- 配置連接配接池 -->
<bean id="masterDataSource" class="com.jolbox.bonecp.BoneCPDataSource"
 destroy-method="close">
 <!-- 資料庫驅動 -->
 <property name="driverClass" value="${jdbc.master.driver}" />
 <!-- 相應驅動的jdbcUrl -->
 <property name="jdbcUrl" value="${jdbc.master.url}" />
 <!-- 資料庫的使用者名 -->
 <property name="username" value="${jdbc.master.username}" />
 <!-- 資料庫的密碼 -->
 <property name="password" value="${jdbc.master.password}" />
 <!-- 檢查資料庫連接配接池中空閑連接配接的間隔時間,機關是分,預設值:240,如果要取消則設定為0 -->
 <property name="idleConnectionTestPeriod" value="60" />
 <!-- 連接配接池中未使用的連結最大存活時間,機關是分,預設值:60,如果要永遠存活設定為0 -->
 <property name="idleMaxAge" value="30" />
 <!-- 每個分區最大的連接配接數 -->
 <property name="maxConnectionsPerPartition" value="150" />
 <!-- 每個分區最小的連接配接數 -->
 <property name="minConnectionsPerPartition" value="5" />
</bean>
 
<!-- 配置連接配接池 -->
<bean id="slave01DataSource" class="com.jolbox.bonecp.BoneCPDataSource"
 destroy-method="close">
 <!-- 資料庫驅動 -->
 <property name="driverClass" value="${jdbc.slave01.driver}" />
 <!-- 相應驅動的jdbcUrl -->
 <property name="jdbcUrl" value="${jdbc.slave01.url}" />
 <!-- 資料庫的使用者名 -->
 <property name="username" value="${jdbc.slave01.username}" />
 <!-- 資料庫的密碼 -->
 <property name="password" value="${jdbc.slave01.password}" />
 <!-- 檢查資料庫連接配接池中空閑連接配接的間隔時間,機關是分,預設值:240,如果要取消則設定為0 -->
 <property name="idleConnectionTestPeriod" value="60" />
 <!-- 連接配接池中未使用的連結最大存活時間,機關是分,預設值:60,如果要永遠存活設定為0 -->
 <property name="idleMaxAge" value="30" />
 <!-- 每個分區最大的連接配接數 -->
 <property name="maxConnectionsPerPartition" value="150" />
 <!-- 每個分區最小的連接配接數 -->
 <property name="minConnectionsPerPartition" value="5" />
</bean>      

定義DataSource

<!-- 定義資料源,使用自己實作的資料源 -->
<bean id="dataSource" class="cn.itcast.usermanage.spring.DynamicDataSource">
 <!-- 設定多個資料源 -->
 <property name="targetDataSources">
  <map key-type="java.lang.String">
   <!-- 這個key需要和程式中的key一緻 -->
   <entry key="master" value-ref="masterDataSource"/>
   <entry key="slave" value-ref="slave01DataSource"/>
  </map>
 </property>
 <!-- 設定預設的資料源,這裡預設走寫庫 -->
 <property name="defaultTargetDataSource" ref="masterDataSource"/>
</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="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>      

定義切面

<!-- 定義AOP切面處理器 -->
<bean class="cn.itcast.usermanage.spring.DataSourceAspect" id="dataSourceAspect" />
 
<aop:config>
 <!-- 定義切面,所有的service的所有方法 -->
 <aop:pointcut id="txPointcut" expression="execution(* xx.xxx.xxxxxxx.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>      

改進切面實作

之前的實作我們是将通過方法名比對,而不是使用事務政策中的定義,我們使用事務管理政策中的規則比對。

改進後的配置

<!-- 定義AOP切面處理器 -->
<bean class="cn.itcast.usermanage.spring.DataSourceAspect" id="dataSourceAspect">
 <!-- 指定事務政策 -->
 <property name="txAdvice" ref="txAdvice"/>
 <!-- 指定slave方法的字首(非必須) -->
 <property name="slaveMethodStart" value="query,find,get"/>
</bean>      

改進後的實作

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.ReflectionUtils;
 
/**
 * 定義資料源的AOP切面,該類控制了使用Master還是Slave。
 * 如果事務管理中配置了事務政策,則采用配置的事務政策中的标記了ReadOnly的方法是用Slave,其它使用Master。
 * 如果沒有配置事務管理的政策,則采用方法名比對的原則,以query、find、get開頭方法用Slave,其它用Master。
 * @author binghe
 *
 */
public class DataSourceAspect {
 
    private List<String> slaveMethodPattern = new ArrayList<String>();
    
    private static final String[] defaultSlaveMethodStart = new String[]{ "query", "find", "get" };
    
    private String[] slaveMethodStart;
 
    /**
     * 讀取事務管理中的政策
     * @param txAdvice
     * @throws Exception
     */
    @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());
        }
    }
 
    /**
     * 在進入Service方法之前執行
     * 
     * @param point 切面對象
     */
    public void before(JoinPoint point) {
        // 擷取到目前執行的方法名
        String methodName = point.getSignature().getName();
 
        boolean isSlave = false;
 
        if (slaveMethodPattern.isEmpty()) {
            // 目前Spring容器中沒有配置事務政策,采用方法名比對方式
            isSlave = isSlave(methodName);
        } else {
            // 使用政策規則比對
            for (String mappedName : slaveMethodPattern) {
                if (isMatch(methodName, mappedName)) {
                    isSlave = true;
                    break;
                }
            }
        }
 
        if (isSlave) {
            // 标記為讀庫
            DynamicDataSourceHolder.markSlave();
        } else {
            // 标記為寫庫
            DynamicDataSourceHolder.markMaster();
        }
    }
 
    /**
     * 判斷是否為讀庫
     * 
     * @param methodName
     * @return
     */
    private Boolean isSlave(String methodName) {
        // 方法名以query、find、get開頭的方法名走從庫
        return StringUtils.startsWithAny(methodName, getSlaveMethodStart());
    }
 
    /**
     * 通配符比對
     * 
     * Return if the given method name matches the mapped name.
     * <p>
     * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, as well as direct
     * equality. Can be overridden in subclasses.
     * 
     * @param methodName the method name of the class
     * @param mappedName the name in the descriptor
     * @return if the names match
     * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
     */
    protected boolean isMatch(String methodName, String mappedName) {
        return PatternMatchUtils.simpleMatch(mappedName, methodName);
    }
 
    /**
     * 使用者指定slave的方法名字首
     * @param slaveMethodStart
     */
    public void setSlaveMethodStart(String[] slaveMethodStart) {
        this.slaveMethodStart = slaveMethodStart;
    }
 
    public String[] getSlaveMethodStart() {
        if(this.slaveMethodStart == null){
            // 沒有指定,使用預設
            return defaultSlaveMethodStart;
        }
        return slaveMethodStart;
    }
    
}      

一主多從的實作

很多實際使用場景下都是采用“一主多從”的架構的,所有我們現在對這種架構做支援,目前隻需要修改DynamicDataSource即可。

【Spring】如何實作多資料源讀寫分離?這是我看過最詳細的一篇!!

實作

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
 
import javax.sql.DataSource;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.util.ReflectionUtils;
 
/**
 * 定義動态資料源,實作通過內建Spring提供的AbstractRoutingDataSource,隻需要實作determineCurrentLookupKey方法即可
 * 由于DynamicDataSource是單例的,線程不安全的,是以采用ThreadLocal保證線程安全,由DynamicDataSourceHolder完成。
 * @author binghe
 *
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
 
    private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class);
 
    private Integer slaveCount;
 
    // 輪詢計數,初始為-1,AtomicInteger是線程安全的
    private AtomicInteger counter = new AtomicInteger(-1);
 
    // 記錄讀庫的key
    private List<Object> slaveDataSources = new ArrayList<Object>(0);
 
    @Override
    protected Object determineCurrentLookupKey() {
        // 使用DynamicDataSourceHolder保證線程安全,并且得到目前線程中的資料源key
        if (DynamicDataSourceHolder.isMaster()) {
            Object key = DynamicDataSourceHolder.getDataSourceKey(); 
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("目前DataSource的key為: " + key);
            }
            return key;
        }
        Object key = getSlaveKey();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("目前DataSource的key為: " + key);
        }
        return key;
 
    }
 
    @SuppressWarnings("unchecked")
    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
 
        // 由于父類的resolvedDataSources屬性是私有的子類擷取不到,需要使用反射擷取
        Field field = ReflectionUtils.findField(AbstractRoutingDataSource.class, "resolvedDataSources");
        field.setAccessible(true); // 設定可通路
 
        try {
            Map<Object, DataSource> resolvedDataSources = (Map<Object, DataSource>) field.get(this);
            // 讀庫的資料量等于資料源總數減去寫庫的數量
            this.slaveCount = resolvedDataSources.size() - 1;
            for (Map.Entry<Object, DataSource> entry : resolvedDataSources.entrySet()) {
                if (DynamicDataSourceHolder.MASTER.equals(entry.getKey())) {
                    continue;
                }
                slaveDataSources.add(entry.getKey());
            }
        } catch (Exception e) {
            LOGGER.error("afterPropertiesSet error! ", e);
        }
    }
 
    /**
     * 輪詢算法實作
     * 
     * @return
     */
    public Object getSlaveKey() {
        // 得到的下标為:0、1、2、3……
        Integer index = counter.incrementAndGet() % slaveCount;
        if (counter.get() > 9999) { // 以免超出Integer範圍
            counter.set(-1); // 還原
        }
        return slaveDataSources.get(index);
    }
 
}      

MySQL主(master)從(slave)複制的原理:

  • master将資料改變記錄到二進制日志(binarylog)中,也即是配置檔案log-bin指定的檔案(這些記錄叫做二進制日志事件,binary log events)
  • slave将master的binary logevents拷貝到它的中繼日志(relay log)
  • slave重做中繼日志中的事件,将改變反映它自己的資料(資料重演)

主從配置需要注意的地方

  • 主DB server和從DB server資料庫的版本一緻
  • 主DB server和從DB server資料庫資料一緻[ 這裡就會可以把主的備份在從上還原,也可以直接将主的資料目錄拷貝到從的相應資料目錄]
  • 主DB server開啟二進制日志,主DB server和從DB server的server_id都必須唯一

主庫配置(windows,Linux下也類似)

在my.ini修改:

#開啟主從複制,主庫的配置
log-bin = mysql3306-bin
#指定主庫serverid
server-id=101
#指定同步的資料庫,如果不指定則同步全部資料庫
binlog-do-db=mybatis_1128      

執行SQL語句查詢狀态:

SHOW MASTER STATUS      
【Spring】如何實作多資料源讀寫分離?這是我看過最詳細的一篇!!

需要記錄下Position值,需要在從庫中設定同步起始值。

在主庫建立同步使用者

#授權使用者slave01使用123456密碼登入mysql
grant replication slave on *.* to 'slave01'@'127.0.0.1' identified by '123456';
flush privileges;      

從庫配置

在my.ini修改

#指定serverid,隻要不重複即可,從庫也隻有這一個配置,其他都在SQL語句中操作
server-id=102      

接下來,從從庫指令行執行如下SQL語句。

CHANGE MASTER TO
 master_host='127.0.0.1',
 master_user='slave01',
 master_password='123456',
 master_port=3306,
 master_log_file='mysql3306-bin.000006',
 master_log_pos=1120;
 
#啟動slave同步
START SLAVE;
 
#檢視同步狀态
SHOW SLAVE STATUS;