spring+mybatis利用interceptor(plugin)兌現數據庫讀寫分離

使用spring的動態路由實現數據庫負載均衡

 

系統中存在的多臺服務器是“地位相當”的,不過,同一時間他們都處於活動(Active)狀態,處於負載均衡等因素考慮,數據訪問請求需要在這幾臺數據庫服務器之間進行合理分配, 這個時候,通過統一的一個DataSource來屏蔽這種請求分配的需求,從而屏蔽數據訪問類與具體DataSource的耦合

系統中存在的多臺數據庫服務器現在地位可能相當也可能不相當,但數據訪問類在系統啓動時間無法明確到底應該使用哪一個數據源進行數據訪問,而必須在系統運行期間通過某種條件來判定到底應該使用哪一個數據源,這個時候,我們也得使用這種“合縱連橫”的方式向數據訪問類暴露一個統一的DataSource,由該DataSource來解除數據訪問類與具體數據源之間的過緊耦合;
更多場景需要讀者根據具體的應用來判定,不過,並非所有的應用要做這樣的處理,如果能夠保持簡單,那儘量保持簡單.要實現這種“合縱連橫”的多數據源管理方式,總的指導原則就是實現一個自定義的DataSource,讓該DataSource來管理系統中存在的多個與具體數據庫掛鉤的數據源, 數據訪問類只跟這個自定義的DataSource打交道即可。在spring2.0.1發佈之前,各個項目中可能存在多種針對這種情況下的多數據源管理方式, 不過,spring2.0.1發佈之後,引入了AbstractRoutingDataSource,使用該類可以實現普遍意義上的多數據源管理功能。

假設我們有三臺數據庫用來實現負載均衡,所有的數據訪問請求最終需要平均的分配到這三臺數據庫服務器之上,那麼,我們可以通過繼承AbstractRoutingDataSource來快速實現一個滿足這樣場景的原型(Prototype):

[java] view plaincopy
 
 
  1. public class PrototypeLoadBalanceDataSource extends AbstractRoutingDataSource  {  
  2.     private Lock lock = new ReentrantLock();  
  3.     private int counter = 0;  
  4.     private int dataSourceNumber = 3;  
  5.     @Override  
  6.     protected Object determineCurrentLookupKey() {  
  7.         lock.lock();  
  8.         try{  
  9.             counter++;  
  10.             int lookupKey = counter % getDataSourceNumber();  
  11.             return new Integer(lookupKey);  
  12.         }finally{  
  13.             lock.unlock();  
  14.         }  
  15.     }  
  16.     // ...  
  17. }  

我們在介紹AbstractRoutingDataSource的時候說過,要繼承該類,通常只需要給出determineCurrentLookupKey()方法的邏輯即可。 下面是針對PrototypeLoadBalanceDataSource的配置:

[html] view plaincopy
 
 
  1. <bean id="dataSourc1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  2.     <property name="url" value=".."/>  
  3.     <property name="driverClassName" value=".."/>  
  4.     <property name="username" value=".."/>  
  5.     <property name="password" value=".."/>  
  6.     <!-- other property settings -->  
  7. </bean>  
  8. <bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  9.     <property name="url" value=".."/>  
  10.     <property name="driverClassName" value=".."/>  
  11.     <property name="username" value=".."/>  
  12.     <property name="password" value=".."/>  
  13.     <!-- other property settings -->  
  14. </bean>  
  15. <bean id="dataSource3" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  16.     <property name="url" value=".."/>  
  17.     <property name="driverClassName" value=".."/>  
  18.     <property name="username" value=".."/>  
  19.     <property name="password" value=".."/>  
  20.     <!-- other property settings -->  
  21. </bean>  
  22. <util:map id="dataSources">  
  23.     <entry key="0" value-ref="dataSource1"/>  
  24.     <entry key="1" value-ref="dataSource2"/>  
  25.     <entry key="2" value-ref="dataSource3"/>  
  26. </util:map>  
  27. <bean id="dataSourceLookup" class="org.springframework.jdbc.datasource.lookup.MapDataSourceLookup">  
  28.     <constructor-arg>  
  29.         <ref bean="dataSources"/>  
  30.     </constructor-arg>  
  31. </bean>  
  32. <bean id="dataSource" class="..PrototypeLoadBalanceDataSource">  
  33.     <property name="defaultTargetDataSource" ref="dataSourc1"/>  
  34.     <property name="targetDataSources" ref="dataSources"/>  
  35.     <property name="dataSourceLookup" ref=""/>  
  36. </bean>  
  37. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
  38.     <property name="dataSource" ref="dataSource"/>  
  39. </bean>  
  40. <bean id="someDao" class="...">  
  41.     <property name=""jdbcTemplate"" ref=""jdbcTemplate""/>  
  42.     <!-- other property settings -->  
  43. </bean>  

使用spring的動態路由實現數據庫讀寫分離

Spring2.0.1以後的版本已經支持配置多數據源,並且可以在運行的時候動態加載不同的數據源。通過繼承AbstractRoutingDataSource就可以實現多數據源的動態轉換。目前做的項目就是需要訪問2個數據源,每個數據源的表結構都是相同的,所以要求數據源的變動對於編碼人員來說是透明,也就是說同樣SQL語句在不同的環境下操作的數據庫是不一樣的。具體的流程如下:

1.建立一個獲得和設置上下文的類

[java] view plaincopy
 
 
  1. package com.lvye.base.dao.impl.jdbc;  
  2. /** 
  3.  *連接哪個數據源的環境變量 
  4.  */  
  5. public class JdbcContextHolder {  
  6.     private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();    
  7.     public static void setJdbcType(String jdbcType) {    
  8.         contextHolder.set(jdbcType);  
  9.     }    
  10.     public static void setSlave(){  
  11.         setJdbcType("slave");  
  12.     }  
  13.     public static void setMaster(){  
  14.         clearJdbcType();  
  15.     }  
  16.     public static String getJdbcType(){    
  17.         return (String) contextHolder.get();   
  18.     }    
  19.     public static void clearJdbcType() {    
  20.         contextHolder.remove();    
  21.     }    
  22. }  

 

2.建立動態數據源類,這個類必須繼承AbstractRoutingDataSource

[java] view plaincopy
 
 
  1. package com.lvye.base.dao.impl.jdbc;  
  2. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;    
  3. public class DynamicDataSource extends AbstractRoutingDataSource{  
  4.     /*(non-Javadoc) 
  5.      *@see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey() 
  6.      *@author wenc 
  7.      */  
  8.      @Override  
  9.      protected Object determineCurrentLookupKey() {  
  10.         return JdbcContextHolder.getJdbcType();  
  11.      }  
  12. }  

這個類實現了determineCurrentLookupKey方法,該方法返回一個Object,一般是返回字符串。該方法中直接使用了JdbcContextHolder.getJdbcType();方法獲得上下文環境並直接返回。

 

3.編寫spring的配置文件配置數據源

[html] view plaincopy
 
 
  1. <beans>  
  2.     <bean id="master" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
  3.         <property name="driverClass">  
  4.             <value>com.mysql.jdbc.Driver</value>  
  5.         </property>  
  6.         <property name="jdbcUrl">  
  7.             <value>jdbc:mysql://192.168.18.143:3306/wenhq?useUnicode=true&characterEncoding=utf-8</value>  
  8.         </property>  
  9.         <property name="user">  
  10.             <value>root</value>  
  11.         </property>  
  12.         <property name="password">  
  13.             <value></value>  
  14.         </property>  
  15.     </bean>  
  16.     <bean id="slave" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">  
  17.         <property name="driverClass">  
  18.             <value>com.mysql.jdbc.Driver</value>  
  19.         </property>  
  20.         <property name="jdbcUrl">  
  21.             <value>jdbc:mysql://192.168.18.144:3306/ wenhq?useUnicode=true&characterEncoding=utf-8</value>  
  22.         </property>  
  23.         <property name="user">  
  24.             <value>root</value>  
  25.         </property>  
  26.         <property name="password">  
  27.             <value></value>  
  28.         </property>  
  29.     </bean>  
  30.     <bean id="mySqlDataSource" class="com.lvye.base.dao.impl.jdbc.DynamicDataSource">   
  31.         <property name="targetDataSources">   
  32.             <map>   
  33.                 <entry key="slave" value-ref="slave"/>   
  34.             </map>   
  35.         </property>   
  36.         <property name="defaultTargetDataSource" ref="master"/>   
  37.     </bean>   
  38.     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
  39.         <property name="dataSource" ref="mySqlDataSource" />  
  40.     </bean>  
  41.     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  42.         <property name="dataSource" ref="mySqlDataSource" />  
  43.     </bean>  
  44. </beans>  

在這個配置中可以看到首先配置兩個真實的數據庫連接,使用的msyql數據庫;master和slave是按照mysql配置的主從關係的數據庫,數據會自動實時同步mySqlDataSource會根據上下文選擇不同的數據源。在這個配置中第一個property屬性配置目標數據源,<entry key="slave" value-ref=" slave"/>中key的值必須要和JdbcContextHolder類中設置的參數值相同,如果有多個值,可以配置多個<entry>標籤。第二個property屬性配置默認的數據源,我們一般默認爲主數據庫。有些朋友喜歡使用hibernate,只需要把上面的jdbcTemplate替換爲hibernate的就可以了。

4.多數據庫連接配置完畢,簡單測試

[java] view plaincopy
 
 
  1. public void testSave() throws Exception{    
  2.     jdbcContextHolder.setSlave();//設置從數據源    
  3.     Test test = new Test();    
  4.     test.setTest("www.wenhq.com.cn");               
  5.     mydao.save(test);//使用dao保存實體             
  6.      jdbcContextHolder.setMaster();//設置主數據源  
  7.     mydao.save(test);//使用dao保存實體到另一個庫中             
  8. }    

 

5.實現讀寫分離,上面的測試通過了,現在就簡單了我的程序是使用jdbc實現的保存數據,只是使用了c3p0的數據庫連接池而已。把所有訪問數據庫的方法包裝一下,統一調用。把執行更新的sql發送到主數據庫了

[java] view plaincopy
 
 
  1. public void execute(String sql) {  
  2.     JdbcContextHolder.setMaster();  
  3.     log.debug("execute-sql:" + sql);  
  4.     jdbcTemplate.execute(sql);  
  5. }      

把查詢的發送到從數據庫,需要注意的是像LAST_INSERT_ID這類的查詢需要特殊處理,必須發送到主數據庫,建議增加專門的方法,用於獲取自增長的主鍵。

[java] view plaincopy
 
 
  1. public List findObject(String queryString, Class clazz) {  
  2.     JdbcContextHolder.setSlave();  
  3.     log.debug("findObject-sql:" + queryString);  
  4.     List list = jdbcTemplate.queryForList(queryString);  
  5.     try {  
  6.         list = StringBase.convertList(list, clazz);// 將List轉化爲List<clazz>  
  7.     } catch (Exception e) {  
  8.         log.error("List convert List<Object> error:" + e);  
  9.     }  
  10.     AbstractRoutingDataSourcereturn list;  
  11. }  

1. 前提

    好長時間不寫博客了,應該吐槽,寫點什麼東西了!最近在研究數據庫讀寫分離,分表分庫的一些東西。其實這個問題好早之前就想好,只是以前使用hibernate,難點是不好判斷什麼樣的sql走讀庫,什麼樣的sql走主庫?用正則匹配開頭或許可以,/^select 沒想出什麼好的解決方法,mybatis就不一樣了,mappedstatement有commandtype屬性,象select,update,delete等類型,爲實現讀寫分離打下來良好的基礎。

2. 解決方法

    LazyConnectionProxy + RoutingDataSource +   Plugin

在SqlSessionTemplate,創建DefaultSqlSession的時候,使用connection proxy的代理,這時並沒有真正的獲取connection,因爲我們不知道是要取讀還是寫的數據源。待到StatementHandler的prepare()使用connection創建PreparedStatement的時候再根據mappedstatement的commandType去路由獲取真實的connection。

   RoutingDataSource支持一主一從,或者一主多從並採用round robin的方式簡單負載均衡,預留接口路由和負載均衡策略可自定義。

   不支持事務,適合auto commit爲true的場景。表述能力

 

applicationContext-common.xml

 

[html] view plain copy
 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.         xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  4.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  5.         xsi:schemaLocation="http://www.springframework.org/schema/beans   
  6.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  7.         http://www.springframework.org/schema/aop   
  8.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  9.         http://www.springframework.org/schema/tx    
  10.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  11.         http://www.springframework.org/schema/context  
  12.         http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  13.   
  14.         <!-- 導入屬性配置文件 -->  
  15.         <context:property-placeholder location="classpath*:*.properties" />  
  16.   
  17.     <bean id="abstractDataSource" abstract="true"  
  18.                 class="com.mchange.v2.c3p0.ComboPooledDataSource"  
  19.                 destroy-method="close">  
  20.                 <property name="driverClass" value="com.mysql.jdbc.Driver" />  
  21.                 <property name="user" value="root" />  
  22.                 <property name="password" value="" />  
  23.         </bean>  
  24.   
  25.         <bean id="readDS" parent="abstractDataSource">  
  26.                 <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test" />  
  27.         </bean>  
  28.           
  29.         <bean id="writeDS" parent="abstractDataSource">  
  30.                 <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test" />  
  31.         </bean>  
  32.           
  33.         <!--簡單的一個master和一個slaver 讀寫分離的數據源 -->  
  34.         <bean id="routingDS" class="com.test.rwmybatis.RoutingDataSource">  
  35.             <property name="targetDataSources">  
  36.                  <map key-type="java.lang.String">  
  37.                      <entry key="read" value-ref="readDS"></entry>  
  38.                      <entry key="write" value-ref="writeDS"></entry>  
  39.                  </map>  
  40.             </property>  
  41.             <property name="defaultTargetDataSource" ref="writeDS"></property>  
  42.         </bean>  
  43.           
  44.         <!-- 適用於一個master和多個slaver的場景,並用roundrobin做負載均衡 -->  
  45.         <bean id="roundRobinDs"  class="com.test.rwmybatis.RoundRobinRWRoutingDataSource">  
  46.               <property name="writeDataSource"  ref="writeDS"></property>  
  47.               <property name="readDataSoures">  
  48.                   <list>  
  49.                       <ref bean="readDS"/>  
  50.                       <ref bean="readDS"/>  
  51.                       <ref bean="readDS"/>  
  52.                   </list>  
  53.               </property>  
  54.               <property name="readKey" value="READ"></property>  
  55.               <property name="writeKey" value="WRITE"></property>  
  56.         </bean>  
  57.           
  58.         <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  59.                 <property name="dataSource" ref="routingDS" />  
  60.                 <property name="configLocation" value="classpath:mybatis-config.xml" />  
  61.                 <!-- mapper和resultmap配置路徑 -->  
  62.                 <property name="mapperLocations">  
  63.                         <list>  
  64.                                 <value>classpath:com/test/rwmybatis/mapper/**/*-Mapper.xml  
  65.                                 </value>  
  66.                         </list>  
  67.                 </property>  
  68.         </bean>  
  69.           
  70.         <bean id="sqlSessionTemplate" class="com.test.rwmybatis.RWSqlSessionTemplate">   
  71.       <constructor-arg ref="sqlSessionFactory" />  
  72.     </bean>  
  73.         <!-- 通過掃描的模式,掃描目錄下所有的mapper, 根據對應的mapper.xml爲其生成代理類-->  
  74.         <bean id="mapper" class="com.test.rwmybatis.RWMapperScannerConfigurer">  
  75.                 <property name="basePackage" value="com.test.rwmybatis.mapper" />  
  76.                 <property name="sqlSessionTemplate" ref="sqlSessionTemplate"></property>  
  77.         </bean>  
  78.   
  79. <!--    <bean id="monitor" class="org.springframework.aop.interceptor.PerformanceMonitorInterceptor"></bean> -->  
  80. <!--    <aop:config> -->  
  81. <!--       <aop:pointcut expression="execution(* com.taofang.smc.persistence..*.*(..))"  id="my_pc"/> -->  
  82. <!--       <aop:advisor advice-ref="monitor" pointcut-ref="my_pc"/> -->  
  83. <!--    </aop:config> -->  
  84. </beans>  
發佈了1165 篇原創文章 · 獲贊 19 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章