自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

【Spring】如何實(shí)現(xiàn)多數(shù)據(jù)源讀寫分離?

開發(fā) 前端
作者個(gè)人研發(fā)的在高并發(fā)場景下,提供的簡單、穩(wěn)定、可擴(kuò)展的延遲消息隊(duì)列框架,具有精準(zhǔn)的定時(shí)任務(wù)和延遲隊(duì)列處理功能。

[[353838]]

作者個(gè)人研發(fā)的在高并發(fā)場景下,提供的簡單、穩(wěn)定、可擴(kuò)展的延遲消息隊(duì)列框架,具有精準(zhǔn)的定時(shí)任務(wù)和延遲隊(duì)列處理功能。自開源半年多以來,已成功為十幾家中小型企業(yè)提供了精準(zhǔn)定時(shí)調(diào)度方案,經(jīng)受住了生產(chǎn)環(huán)境的考驗(yàn)。為使更多童鞋受益,現(xiàn)給出開源框架地址:https://github.com/sunshinelyz/mykit-delay

寫在前面

很多小伙伴私聊我說:最近他們公司的業(yè)務(wù)涉及到多個(gè)數(shù)據(jù)源的問題,問我Spring如何實(shí)現(xiàn)多數(shù)據(jù)源的問題?;卮疬@個(gè)問題之前,首先需要弄懂什么是多數(shù)據(jù)源:多數(shù)據(jù)源就是在同一個(gè)項(xiàng)目中,會(huì)連接兩個(gè)甚至多個(gè)數(shù)據(jù)存儲(chǔ),這里的數(shù)據(jù)存儲(chǔ)可以是關(guān)系型數(shù)據(jù)庫(比如:MySQL、SQL Server、Oracle),也可以非關(guān)系型數(shù)據(jù)庫,比如:HBase、MongoDB、ES等。那么,問題來了,Spring能夠?qū)崿F(xiàn)多數(shù)據(jù)源嗎?并且還要實(shí)現(xiàn)讀者分離?答案是:必須的,這么強(qiáng)大的Spring,肯定能實(shí)現(xiàn)啊!別急,我們就一點(diǎn)點(diǎn)剖析、解決這些問題!

背景

我們一般應(yīng)用對(duì)數(shù)據(jù)庫而言都是“讀多寫少”,也就說對(duì)數(shù)據(jù)庫讀取數(shù)據(jù)的壓力比較大,有一個(gè)思路就是說采用數(shù)據(jù)庫集群的方案,

其中一個(gè)是主庫,負(fù)責(zé)寫入數(shù)據(jù),我們稱之為:寫庫;其它都是從庫,負(fù)責(zé)讀取數(shù)據(jù),我們稱之為:讀庫;

那么,對(duì)我們的要求是:

  • 讀庫和寫庫的數(shù)據(jù)一致;
  • 寫數(shù)據(jù)必須寫到寫庫;
  • 讀數(shù)據(jù)必須到讀庫;

方案

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

應(yīng)用層解決

 

優(yōu)點(diǎn):

  • 多數(shù)據(jù)源切換方便,由程序自動(dòng)完成;
  • 不需要引入中間件;
  • 理論上支持任何數(shù)據(jù)庫;

缺點(diǎn):

  • 由程序員完成,運(yùn)維參與不到;
  • 不能做到動(dòng)態(tài)增加數(shù)據(jù)源;

中間件解決

 

優(yōu)點(diǎn):

  • 源程序不需要做任何改動(dòng)就可以實(shí)現(xiàn)讀寫分離;
  • 動(dòng)態(tài)添加數(shù)據(jù)源不需要重啟程序;

缺點(diǎn):

  • 程序依賴于中間件,會(huì)導(dǎo)致切換數(shù)據(jù)庫變得困難;
  • 由中間件做了中轉(zhuǎn)代理,性能有所下降;

Spring方案

原理

 

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

DynamicDataSource

  1. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 
  2.   
  3. /** 
  4.  * 定義動(dòng)態(tài)數(shù)據(jù)源,實(shí)現(xiàn)通過集成Spring提供的AbstractRoutingDataSource,只需要實(shí)現(xiàn)determineCurrentLookupKey方法即可 
  5.  * 由于DynamicDataSource是單例的,線程不安全的,所以采用ThreadLocal保證線程安全,由DynamicDataSourceHolder完成。 
  6.  * @author binghe 
  7.  */ 
  8. public class DynamicDataSource extends AbstractRoutingDataSource{ 
  9.   
  10.     @Override 
  11.     protected Object determineCurrentLookupKey() { 
  12.         // 使用DynamicDataSourceHolder保證線程安全,并且得到當(dāng)前線程中的數(shù)據(jù)源key 
  13.         return DynamicDataSourceHolder.getDataSourceKey(); 
  14.     } 
  15.   

DynamicDataSourceHolder

  1. /** 
  2.  * 使用ThreadLocal技術(shù)來記錄當(dāng)前線程中的數(shù)據(jù)源的key 
  3.  * @author binghe 
  4.  */ 
  5. public class DynamicDataSourceHolder { 
  6.      
  7.     //寫庫對(duì)應(yīng)的數(shù)據(jù)源key 
  8.     private static final String MASTER = "master"
  9.   
  10.     //讀庫對(duì)應(yīng)的數(shù)據(jù)源key 
  11.     private static final String SLAVE = "slave"
  12.      
  13.     //使用ThreadLocal記錄當(dāng)前線程的數(shù)據(jù)源key 
  14.     private static final ThreadLocal<String> holder = new ThreadLocal<String>(); 
  15.   
  16.     /** 
  17.      * 設(shè)置數(shù)據(jù)源key 
  18.      * @param key 
  19.      */ 
  20.     public static void putDataSourceKey(String key) { 
  21.         holder.set(key); 
  22.     } 
  23.   
  24.     /** 
  25.      * 獲取數(shù)據(jù)源key 
  26.      * @return 
  27.      */ 
  28.     public static String getDataSourceKey() { 
  29.         return holder.get(); 
  30.     } 
  31.      
  32.     /** 
  33.      * 標(biāo)記寫庫 
  34.      */ 
  35.     public static void markMaster(){ 
  36.         putDataSourceKey(MASTER); 
  37.     } 
  38.      
  39.     /** 
  40.      * 標(biāo)記讀庫 
  41.      */ 
  42.     public static void markSlave(){ 
  43.         putDataSourceKey(SLAVE); 
  44.     } 
  45.   

DataSourceAspect

  1. import org.apache.commons.lang3.StringUtils; 
  2. import org.aspectj.lang.JoinPoint; 
  3.   
  4. /** 
  5.  * 定義數(shù)據(jù)源的AOP切面,通過該Service的方法名判斷是應(yīng)該走讀庫還是寫庫 
  6.  * @author binghe 
  7.  */ 
  8. public class DataSourceAspect { 
  9.   
  10.     /** 
  11.      * 在進(jìn)入Service方法之前執(zhí)行 
  12.      * @param point 切面對(duì)象 
  13.      */ 
  14.     public void before(JoinPoint point) { 
  15.         // 獲取到當(dāng)前執(zhí)行的方法名 
  16.         String methodName = point.getSignature().getName(); 
  17.         if (isSlave(methodName)) { 
  18.             // 標(biāo)記為讀庫 
  19.             DynamicDataSourceHolder.markSlave(); 
  20.         } else { 
  21.             // 標(biāo)記為寫庫 
  22.             DynamicDataSourceHolder.markMaster(); 
  23.         } 
  24.     } 
  25.   
  26.     /** 
  27.      * 判斷是否為讀庫 
  28.      *  
  29.      * @param methodName 
  30.      * @return 
  31.      */ 
  32.     private Boolean isSlave(String methodName) { 
  33.         // 方法名以query、find、get開頭的方法名走從庫 
  34.         return StringUtils.startsWithAny(methodName, "query""find""get"); 
  35.     } 
  36.   

配置2個(gè)數(shù)據(jù)源

jdbc.properties

  1. jdbc.master.driver=com.mysql.jdbc.Driver 
  2. jdbc.master.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true 
  3. jdbc.master.username=root 
  4. jdbc.master.password=123456 
  5.  
  6.  
  7. jdbc.slave01.driver=com.mysql.jdbc.Driver 
  8. jdbc.slave01.url=jdbc:mysql://127.0.0.1:3307/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true 
  9. jdbc.slave01.username=root 
  10. jdbc.slave01.password=123456 

定義連接池

  1. <!-- 配置連接池 --> 
  2. <bean id="masterDataSource" class="com.jolbox.bonecp.BoneCPDataSource" 
  3.  destroy-method="close"
  4.  <!-- 數(shù)據(jù)庫驅(qū)動(dòng) --> 
  5.  <property name="driverClass" value="${jdbc.master.driver}" /> 
  6.  <!-- 相應(yīng)驅(qū)動(dòng)的jdbcUrl --> 
  7.  <property name="jdbcUrl" value="${jdbc.master.url}" /> 
  8.  <!-- 數(shù)據(jù)庫的用戶名 --> 
  9.  <property name="username" value="${jdbc.master.username}" /> 
  10.  <!-- 數(shù)據(jù)庫的密碼 --> 
  11.  <property name="password" value="${jdbc.master.password}" /> 
  12.  <!-- 檢查數(shù)據(jù)庫連接池中空閑連接的間隔時(shí)間,單位是分,默認(rèn)值:240,如果要取消則設(shè)置為0 --> 
  13.  <property name="idleConnectionTestPeriod" value="60" /> 
  14.  <!-- 連接池中未使用的鏈接最大存活時(shí)間,單位是分,默認(rèn)值:60,如果要永遠(yuǎn)存活設(shè)置為0 --> 
  15.  <property name="idleMaxAge" value="30" /> 
  16.  <!-- 每個(gè)分區(qū)最大的連接數(shù) --> 
  17.  <property name="maxConnectionsPerPartition" value="150" /> 
  18.  <!-- 每個(gè)分區(qū)最小的連接數(shù) --> 
  19.  <property name="minConnectionsPerPartition" value="5" /> 
  20. </bean> 
  21.   
  22. <!-- 配置連接池 --> 
  23. <bean id="slave01DataSource" class="com.jolbox.bonecp.BoneCPDataSource" 
  24.  destroy-method="close"
  25.  <!-- 數(shù)據(jù)庫驅(qū)動(dòng) --> 
  26.  <property name="driverClass" value="${jdbc.slave01.driver}" /> 
  27.  <!-- 相應(yīng)驅(qū)動(dòng)的jdbcUrl --> 
  28.  <property name="jdbcUrl" value="${jdbc.slave01.url}" /> 
  29.  <!-- 數(shù)據(jù)庫的用戶名 --> 
  30.  <property name="username" value="${jdbc.slave01.username}" /> 
  31.  <!-- 數(shù)據(jù)庫的密碼 --> 
  32.  <property name="password" value="${jdbc.slave01.password}" /> 
  33.  <!-- 檢查數(shù)據(jù)庫連接池中空閑連接的間隔時(shí)間,單位是分,默認(rèn)值:240,如果要取消則設(shè)置為0 --> 
  34.  <property name="idleConnectionTestPeriod" value="60" /> 
  35.  <!-- 連接池中未使用的鏈接最大存活時(shí)間,單位是分,默認(rèn)值:60,如果要永遠(yuǎn)存活設(shè)置為0 --> 
  36.  <property name="idleMaxAge" value="30" /> 
  37.  <!-- 每個(gè)分區(qū)最大的連接數(shù) --> 
  38.  <property name="maxConnectionsPerPartition" value="150" /> 
  39.  <!-- 每個(gè)分區(qū)最小的連接數(shù) --> 
  40.  <property name="minConnectionsPerPartition" value="5" /> 
  41. </bean> 

定義DataSource

  1. <!-- 定義數(shù)據(jù)源,使用自己實(shí)現(xiàn)的數(shù)據(jù)源 --> 
  2. <bean id="dataSource" class="cn.itcast.usermanage.spring.DynamicDataSource"
  3.  <!-- 設(shè)置多個(gè)數(shù)據(jù)源 --> 
  4.  <property name="targetDataSources"
  5.   <map key-type="java.lang.String"
  6.    <!-- 這個(gè)key需要和程序中的key一致 --> 
  7.    <entry key="master" value-ref="masterDataSource"/> 
  8.    <entry key="slave" value-ref="slave01DataSource"/> 
  9.   </map> 
  10.  </property> 
  11.  <!-- 設(shè)置默認(rèn)的數(shù)據(jù)源,這里默認(rèn)走寫庫 --> 
  12.  <property name="defaultTargetDataSource" ref="masterDataSource"/> 
  13. </bean> 

配置事務(wù)管理與動(dòng)態(tài)切面

定義事務(wù)管理器

  1. <!-- 定義事務(wù)管理器 --> 
  2. <bean id="transactionManager" 
  3.  class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
  4.  <property name="dataSource" ref="dataSource" /> 
  5. </bean> 

定義事務(wù)策略

  1. <!-- 定義事務(wù)策略 --> 
  2. <tx:advice id="txAdvice" transaction-manager="transactionManager"
  3.  <tx:attributes> 
  4.   <!--定義查詢方法都是只讀的 --> 
  5.   <tx:method name="query*" read-only="true" /> 
  6.   <tx:method name="find*" read-only="true" /> 
  7.   <tx:method name="get*" read-only="true" /> 
  8.   
  9.   <!-- 主庫執(zhí)行操作,事務(wù)傳播行為定義為默認(rèn)行為 --> 
  10.   <tx:method name="save*" propagation="REQUIRED" /> 
  11.   <tx:method name="update*" propagation="REQUIRED" /> 
  12.   <tx:method name="delete*" propagation="REQUIRED" /> 
  13.   
  14.   <!--其他方法使用默認(rèn)事務(wù)策略 --> 
  15.   <tx:method name="*" /> 
  16.  </tx:attributes> 
  17. </tx:advice> 

定義切面

  1. <!-- 定義AOP切面處理器 --> 
  2. <bean class="cn.itcast.usermanage.spring.DataSourceAspect" id="dataSourceAspect" /> 
  3.   
  4. <aop:config> 
  5.  <!-- 定義切面,所有的service的所有方法 --> 
  6.  <aop:pointcut id="txPointcut" expression="execution(* xx.xxx.xxxxxxx.service.*.*(..))" /> 
  7.  <!-- 應(yīng)用事務(wù)策略到Service切面 --> 
  8.  <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> 
  9.   
  10.  <!-- 將切面應(yīng)用到自定義的切面處理器上,-9999保證該切面優(yōu)先級(jí)最高執(zhí)行 --> 
  11.  <aop:aspect ref="dataSourceAspect" order="-9999"
  12.   <aop:before method="before" pointcut-ref="txPointcut" /> 
  13.  </aop:aspect> 
  14. </aop:config> 

改進(jìn)切面實(shí)現(xiàn)

之前的實(shí)現(xiàn)我們是將通過方法名匹配,而不是使用事務(wù)策略中的定義,我們使用事務(wù)管理策略中的規(guī)則匹配。

改進(jìn)后的配置

  1. <!-- 定義AOP切面處理器 --> 
  2. <bean class="cn.itcast.usermanage.spring.DataSourceAspect" id="dataSourceAspect"
  3.  <!-- 指定事務(wù)策略 --> 
  4.  <property name="txAdvice" ref="txAdvice"/> 
  5.  <!-- 指定slave方法的前綴(非必須) --> 
  6.  <property name="slaveMethodStart" value="query,find,get"/> 
  7. </bean> 

改進(jìn)后的實(shí)現(xiàn)

  1. import java.lang.reflect.Field; 
  2. import java.util.ArrayList; 
  3. import java.util.List; 
  4. import java.util.Map; 
  5.   
  6. import org.apache.commons.lang3.StringUtils; 
  7. import org.aspectj.lang.JoinPoint; 
  8. import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource; 
  9. import org.springframework.transaction.interceptor.TransactionAttribute; 
  10. import org.springframework.transaction.interceptor.TransactionAttributeSource; 
  11. import org.springframework.transaction.interceptor.TransactionInterceptor; 
  12. import org.springframework.util.PatternMatchUtils; 
  13. import org.springframework.util.ReflectionUtils; 
  14.   
  15. /** 
  16.  * 定義數(shù)據(jù)源的AOP切面,該類控制了使用Master還是Slave。 
  17.  * 如果事務(wù)管理中配置了事務(wù)策略,則采用配置的事務(wù)策略中的標(biāo)記了ReadOnly的方法是用Slave,其它使用Master。 
  18.  * 如果沒有配置事務(wù)管理的策略,則采用方法名匹配的原則,以query、find、get開頭方法用Slave,其它用Master。 
  19.  * @author binghe 
  20.  * 
  21.  */ 
  22. public class DataSourceAspect { 
  23.   
  24.     private List<String> slaveMethodPattern = new ArrayList<String>(); 
  25.      
  26.     private static final String[] defaultSlaveMethodStart = new String[]{ "query""find""get" }; 
  27.      
  28.     private String[] slaveMethodStart; 
  29.   
  30.     /** 
  31.      * 讀取事務(wù)管理中的策略 
  32.      * @param txAdvice 
  33.      * @throws Exception 
  34.      */ 
  35.     @SuppressWarnings("unchecked"
  36.     public void setTxAdvice(TransactionInterceptor txAdvice) throws Exception { 
  37.         if (txAdvice == null) { 
  38.             // 沒有配置事務(wù)管理策略 
  39.             return
  40.         } 
  41.         //從txAdvice獲取到策略配置信息 
  42.         TransactionAttributeSource transactionAttributeSource = txAdvice.getTransactionAttributeSource(); 
  43.         if (!(transactionAttributeSource instanceof NameMatchTransactionAttributeSource)) { 
  44.             return
  45.         } 
  46.         //使用反射技術(shù)獲取到NameMatchTransactionAttributeSource對(duì)象中的nameMap屬性值 
  47.         NameMatchTransactionAttributeSource matchTransactionAttributeSource = (NameMatchTransactionAttributeSource) transactionAttributeSource; 
  48.         Field nameMapField = ReflectionUtils.findField(NameMatchTransactionAttributeSource.class, "nameMap"); 
  49.         nameMapField.setAccessible(true); //設(shè)置該字段可訪問 
  50.         //獲取nameMap的值 
  51.         Map<String, TransactionAttribute> map = (Map<String, TransactionAttribute>) nameMapField.get(matchTransactionAttributeSource); 
  52.   
  53.         //遍歷nameMap 
  54.         for (Map.Entry<String, TransactionAttribute> entry : map.entrySet()) { 
  55.             if (!entry.getValue().isReadOnly()) {//判斷之后定義了ReadOnly的策略才加入到slaveMethodPattern 
  56.                 continue
  57.             } 
  58.             slaveMethodPattern.add(entry.getKey()); 
  59.         } 
  60.     } 
  61.   
  62.     /** 
  63.      * 在進(jìn)入Service方法之前執(zhí)行 
  64.      *  
  65.      * @param point 切面對(duì)象 
  66.      */ 
  67.     public void before(JoinPoint point) { 
  68.         // 獲取到當(dāng)前執(zhí)行的方法名 
  69.         String methodName = point.getSignature().getName(); 
  70.   
  71.         boolean isSlave = false
  72.   
  73.         if (slaveMethodPattern.isEmpty()) { 
  74.             // 當(dāng)前Spring容器中沒有配置事務(wù)策略,采用方法名匹配方式 
  75.             isSlave = isSlave(methodName); 
  76.         } else { 
  77.             // 使用策略規(guī)則匹配 
  78.             for (String mappedName : slaveMethodPattern) { 
  79.                 if (isMatch(methodName, mappedName)) { 
  80.                     isSlave = true
  81.                     break; 
  82.                 } 
  83.             } 
  84.         } 
  85.   
  86.         if (isSlave) { 
  87.             // 標(biāo)記為讀庫 
  88.             DynamicDataSourceHolder.markSlave(); 
  89.         } else { 
  90.             // 標(biāo)記為寫庫 
  91.             DynamicDataSourceHolder.markMaster(); 
  92.         } 
  93.     } 
  94.   
  95.     /** 
  96.      * 判斷是否為讀庫 
  97.      *  
  98.      * @param methodName 
  99.      * @return 
  100.      */ 
  101.     private Boolean isSlave(String methodName) { 
  102.         // 方法名以query、find、get開頭的方法名走從庫 
  103.         return StringUtils.startsWithAny(methodName, getSlaveMethodStart()); 
  104.     } 
  105.   
  106.     /** 
  107.      * 通配符匹配 
  108.      *  
  109.      * Return if the given method name matches the mapped name
  110.      * <p> 
  111.      * The default implementation checks for "xxx*""*xxx" and "*xxx*" matches, as well as direct 
  112.      * equality. Can be overridden in subclasses. 
  113.      *  
  114.      * @param methodName the method name of the class 
  115.      * @param mappedName the name in the descriptor 
  116.      * @return if the names match 
  117.      * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String) 
  118.      */ 
  119.     protected boolean isMatch(String methodName, String mappedName) { 
  120.         return PatternMatchUtils.simpleMatch(mappedName, methodName); 
  121.     } 
  122.   
  123.     /** 
  124.      * 用戶指定slave的方法名前綴 
  125.      * @param slaveMethodStart 
  126.      */ 
  127.     public void setSlaveMethodStart(String[] slaveMethodStart) { 
  128.         this.slaveMethodStart = slaveMethodStart; 
  129.     } 
  130.   
  131.     public String[] getSlaveMethodStart() { 
  132.         if(this.slaveMethodStart == null){ 
  133.             // 沒有指定,使用默認(rèn) 
  134.             return defaultSlaveMethodStart; 
  135.         } 
  136.         return slaveMethodStart; 
  137.     } 
  138.      

一主多從的實(shí)現(xiàn)

很多實(shí)際使用場景下都是采用“一主多從”的架構(gòu)的,所有我們現(xiàn)在對(duì)這種架構(gòu)做支持,目前只需要修改DynamicDataSource即可。

 

實(shí)現(xiàn)

  1. import java.lang.reflect.Field; 
  2. import java.util.ArrayList; 
  3. import java.util.List; 
  4. import java.util.Map; 
  5. import java.util.concurrent.atomic.AtomicInteger; 
  6.   
  7. import javax.sql.DataSource; 
  8.   
  9. import org.slf4j.Logger; 
  10. import org.slf4j.LoggerFactory; 
  11. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 
  12. import org.springframework.util.ReflectionUtils; 
  13.   
  14. /** 
  15.  * 定義動(dòng)態(tài)數(shù)據(jù)源,實(shí)現(xiàn)通過集成Spring提供的AbstractRoutingDataSource,只需要實(shí)現(xiàn)determineCurrentLookupKey方法即可 
  16.  * 由于DynamicDataSource是單例的,線程不安全的,所以采用ThreadLocal保證線程安全,由DynamicDataSourceHolder完成。 
  17.  * @author binghe 
  18.  * 
  19.  */ 
  20. public class DynamicDataSource extends AbstractRoutingDataSource { 
  21.   
  22.     private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class); 
  23.   
  24.     private Integer slaveCount; 
  25.   
  26.     // 輪詢計(jì)數(shù),初始為-1,AtomicInteger是線程安全的 
  27.     private AtomicInteger counter = new AtomicInteger(-1); 
  28.   
  29.     // 記錄讀庫的key 
  30.     private List<Object> slaveDataSources = new ArrayList<Object>(0); 
  31.   
  32.     @Override 
  33.     protected Object determineCurrentLookupKey() { 
  34.         // 使用DynamicDataSourceHolder保證線程安全,并且得到當(dāng)前線程中的數(shù)據(jù)源key 
  35.         if (DynamicDataSourceHolder.isMaster()) { 
  36.             Object key = DynamicDataSourceHolder.getDataSourceKey();  
  37.             if (LOGGER.isDebugEnabled()) { 
  38.                 LOGGER.debug("當(dāng)前DataSource的key為: " + key); 
  39.             } 
  40.             return key
  41.         } 
  42.         Object key = getSlaveKey(); 
  43.         if (LOGGER.isDebugEnabled()) { 
  44.             LOGGER.debug("當(dāng)前DataSource的key為: " + key); 
  45.         } 
  46.         return key
  47.   
  48.     } 
  49.   
  50.     @SuppressWarnings("unchecked"
  51.     @Override 
  52.     public void afterPropertiesSet() { 
  53.         super.afterPropertiesSet(); 
  54.   
  55.         // 由于父類的resolvedDataSources屬性是私有的子類獲取不到,需要使用反射獲取 
  56.         Field field = ReflectionUtils.findField(AbstractRoutingDataSource.class, "resolvedDataSources"); 
  57.         field.setAccessible(true); // 設(shè)置可訪問 
  58.   
  59.         try { 
  60.             Map<Object, DataSource> resolvedDataSources = (Map<Object, DataSource>) field.get(this); 
  61.             // 讀庫的數(shù)據(jù)量等于數(shù)據(jù)源總數(shù)減去寫庫的數(shù)量 
  62.             this.slaveCount = resolvedDataSources.size() - 1; 
  63.             for (Map.Entry<Object, DataSource> entry : resolvedDataSources.entrySet()) { 
  64.                 if (DynamicDataSourceHolder.MASTER.equals(entry.getKey())) { 
  65.                     continue
  66.                 } 
  67.                 slaveDataSources.add(entry.getKey()); 
  68.             } 
  69.         } catch (Exception e) { 
  70.             LOGGER.error("afterPropertiesSet error! ", e); 
  71.         } 
  72.     } 
  73.   
  74.     /** 
  75.      * 輪詢算法實(shí)現(xiàn) 
  76.      *  
  77.      * @return 
  78.      */ 
  79.     public Object getSlaveKey() { 
  80.         // 得到的下標(biāo)為:0、1、2、3…… 
  81.         Integer index = counter.incrementAndGet() % slaveCount; 
  82.         if (counter.get() > 9999) { // 以免超出Integer范圍 
  83.             counter.set(-1); // 還原 
  84.         } 
  85.         return slaveDataSources.get(index); 
  86.     } 
  87.   

MySQL主從復(fù)制

原理

 

MySQL主(master)從(slave)復(fù)制的原理:

  • master將數(shù)據(jù)改變記錄到二進(jìn)制日志(binarylog)中,也即是配置文件log-bin指定的文件(這些記錄叫做二進(jìn)制日志事件,binary log events)
  • slave將master的binary logevents拷貝到它的中繼日志(relay log)
  • slave重做中繼日志中的事件,將改變反映它自己的數(shù)據(jù)(數(shù)據(jù)重演)

主從配置需要注意的地方

  • 主DB server和從DB server數(shù)據(jù)庫的版本一致
  • 主DB server和從DB server數(shù)據(jù)庫數(shù)據(jù)一致[ 這里就會(huì)可以把主的備份在從上還原,也可以直接將主的數(shù)據(jù)目錄拷貝到從的相應(yīng)數(shù)據(jù)目錄]
  • 主DB server開啟二進(jìn)制日志,主DB server和從DB server的server_id都必須唯一

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

在my.ini修改:

  1. #開啟主從復(fù)制,主庫的配置 
  2. log-bin = mysql3306-bin 
  3. #指定主庫serverid 
  4. server-id=101 
  5. #指定同步的數(shù)據(jù)庫,如果不指定則同步全部數(shù)據(jù)庫 
  6. binlog-do-db=mybatis_1128 

執(zhí)行SQL語句查詢狀態(tài):

  1. SHOW MASTER STATUS 

 

需要記錄下Position值,需要在從庫中設(shè)置同步起始值。

在主庫創(chuàng)建同步用戶

  1. #授權(quán)用戶slave01使用123456密碼登錄mysql 
  2. grant replication slave on *.* to 'slave01'@'127.0.0.1' identified by '123456'
  3. flush privileges

從庫配置

在my.ini修改

  1. #指定serverid,只要不重復(fù)即可,從庫也只有這一個(gè)配置,其他都在SQL語句中操作 
  2. server-id=102 

接下來,從從庫命令行執(zhí)行如下SQL語句。

  1. CHANGE MASTER TO 
  2.  master_host='127.0.0.1'
  3.  master_user='slave01'
  4.  master_password='123456'
  5.  master_port=3306, 
  6.  master_log_file='mysql3306-bin.000006'
  7.  master_log_pos=1120; 
  8.   
  9. #啟動(dòng)slave同步 
  10. START SLAVE; 
  11.   
  12. #查看同步狀態(tài) 
  13. SHOW SLAVE STATUS; 

 

 

責(zé)任編輯:武曉燕 來源: 冰河技術(shù)
相關(guān)推薦

2023-09-07 08:39:39

copy屬性數(shù)據(jù)源

2020-12-31 07:55:33

spring bootMybatis數(shù)據(jù)庫

2009-08-14 10:26:27

ibatis多數(shù)據(jù)源

2022-05-18 12:04:19

Mybatis數(shù)據(jù)源Spring

2023-10-18 15:25:29

數(shù)據(jù)源數(shù)據(jù)庫

2024-10-30 10:22:17

2022-12-19 07:21:35

Hutool-db數(shù)據(jù)庫JDBC

2023-06-07 08:08:37

MybatisSpringBoot

2022-06-02 10:38:42

微服務(wù)數(shù)據(jù)源分布式

2021-09-08 10:23:08

讀寫分離Java數(shù)據(jù)庫

2020-06-02 07:55:31

SpringBoot多數(shù)據(jù)源

2023-10-31 07:52:53

多數(shù)據(jù)源管理后端

2023-01-04 09:33:31

SpringBootMybatis

2025-04-14 01:00:00

Calcite電商系統(tǒng)MySQL

2025-01-17 09:11:51

2022-05-10 10:43:35

數(shù)據(jù)源動(dòng)態(tài)切換Spring

2020-03-13 14:05:14

SpringBoot+數(shù)據(jù)源Java

2025-02-05 09:17:40

2023-12-13 12:20:36

SpringMySQL數(shù)據(jù)源

2023-01-10 16:30:22

Spring數(shù)據(jù)庫
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)