前言
開發中常用到主從數據庫來提高系統的性能。怎么樣才能方便的實現主從讀寫分離呢?近日工作任務較輕,有空學習學習技術,遂來研究如果實現讀寫分離。這里用博客記錄下過程,一方面可備日后查看,同時也能分享給大家(網上的資料真的大都是抄來抄去,,還不帶格式的,看的真心難受)。
下面話不多說了,來一起看看詳細的介紹吧。
1、背景
一個項目中數據庫最基礎同時也是最主流的是單機數據庫,讀寫都在一個庫中。當用戶逐漸增多,單機數據庫無法滿足性能要求時,就會進行讀寫分離改造(適用于讀多寫少),寫操作一個庫,讀操作多個庫,通常會做一個數據庫集群,開啟主從備份,一主多從,以提高讀取性能。當用戶更多讀寫分離也無法滿足時,就需要分布式數據庫了(可能以后會學習怎么弄)。
正常情況下讀寫分離的實現,首先要做一個一主多從的數據庫集群,同時還需要進行數據同步。這一篇記錄如何用mysql搭建一個一主多次的配置,下一篇記錄代碼層面如何實現讀寫分離。
2、搭建一主多從數據庫集群
主從備份需要多臺虛擬機,我是用wmware完整克隆多個實例,注意直接克隆的虛擬機會導致每個數據庫的uuid相同,需要修改為不同的uuid。修改方法參考這個:點擊跳轉。
主庫配置
主數據庫(master)中新建一個用戶用于從數據庫(slave)讀取主數據庫二進制日志,sql語句如下:
1
2
3
|
mysql> create user 'repl' @ '%' identified by '123456' ;#創建用戶 mysql> grant replication slave on *.* to 'repl' @ '%' ;#分配權限 mysql>flush privileges; #刷新權限 |
同時修改mysql配置文件開啟二進制日志,新增部分如下:
1
2
3
4
|
[mysqld] server-id= 1 log-bin=master-bin log-bin-index=master-bin.index |
然后重啟數據庫,使用show master status;
語句查看主庫狀態,如下所示:
從庫配置
同樣先新增幾行配置:
1
2
3
4
|
[mysqld] server-id= 2 relay-log-index=slave-relay-bin.index relay-log=slave-relay-bin |
然后重啟數據庫,使用如下語句連接主庫:
1
2
3
4
5
6
|
change master to master_host= '192.168.226.5' , master_user= 'root' , master_password= '123456' , master_log_file= 'master-bin.000003' , master_log_pos= 154 ; |
接著運行start slave;
開啟備份,正常情況如下圖所示:slave_io_running和slave_sql_running都為yes。
可以用這個步驟開啟多個從庫。
默認情況下備份是主庫的全部操作都會備份到從庫,實際可能需要忽略某些庫,可以在主庫中增加如下配置:
1
2
3
4
5
6
7
|
# 不同步哪些數據庫 binlog-ignore-db = mysql binlog-ignore-db = test binlog-ignore-db = information_schema # 只同步哪些數據庫,除此之外,其他不同步 binlog- do -db = game |
3、代碼層面進行讀寫分離
代碼環境是springboot+mybatis+druib連接池。想要讀寫分離就需要配置多個數據源,在進行寫操作是選擇寫的數據源,讀操作時選擇讀的數據源。其中有兩個關鍵點:
- 如何切換數據源
- 如何根據不同的方法選擇正確的數據源
1)、如何切換數據源
通常用springboot時都是使用它的默認配置,只需要在配置文件中定義好連接屬性就行了,但是現在我們需要自己來配置了,spring是支持多數據源的,多個datasource放在一個hashmaptargetdatasource中,通過derterminecurrentlookupkey獲取key來覺定要使用哪個數據源。因此我們的目標就很明確了,建立多個datasource放到targetdatasource中,同時重寫derterminecurrentlookupkey方法來決定使用哪個key。
2)、如何選擇數據源
事務一般是注解在service層的,因此在開始這個service方法調用時要確定數據源,有什么通用方法能夠在開始執行一個方法前做操作呢?相信你已經想到了那就是切面 。怎么切有兩種辦法:
- 注解式,定義一個只讀注解,被該數據標注的方法使用讀庫
- 方法名,根據方法名寫切點,比如getxxx用讀庫,setxxx用寫庫
3)、代碼編寫
a、編寫配置文件,配置兩個數據源信息
只有必填信息,其他都有默認設置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
mysql: datasource: #讀庫數目 num: 1 type-aliases- package : com.example.dxfl.dao mapper-locations: classpath:/mapper/*.xml config-location: classpath:/mybatis-config.xml write: url: jdbc:mysql: //192.168.226.5:3306/test?useunicode=true&characterencoding=utf-8&usessl=true username: root password: 123456 driver- class -name: com.mysql.jdbc.driver read: url: jdbc:mysql: //192.168.226.6:3306/test?useunicode=true&characterencoding=utf-8&usessl=true username: root password: 123456 driver- class -name: com.mysql.jdbc.driver |
b、編寫dbcontextholder類
這個類用來設置數據庫類別,其中有一個threadlocal用來保存每個線程的是使用讀庫,還是寫庫。代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
/** * description 這里切換讀/寫模式 * 原理是利用threadlocal保存當前線程是否處于讀模式(通過開始read_only注解在開始操作前設置模式為讀模式, * 操作結束后清除該數據,避免內存泄漏,同時也為了后續在該線程進行寫操作時任然為讀模式 * @author fxb * @date 2018-08-31 */ public class dbcontextholder { private static logger log = loggerfactory.getlogger(dbcontextholder. class ); public static final string write = "write" ; public static final string read = "read" ; private static threadlocal<string> contextholder= new threadlocal<>(); public static void setdbtype(string dbtype) { if (dbtype == null ) { log.error( "dbtype為空" ); throw new nullpointerexception(); } log.info( "設置dbtype為:{}" ,dbtype); contextholder.set(dbtype); } public static string getdbtype() { return contextholder.get() == null ? write : contextholder.get(); } public static void cleardbtype() { contextholder.remove(); } } |
c、重寫determinecurrentlookupkey方法
spring在開始進行數據庫操作時會通過這個方法來決定使用哪個數據庫,因此我們在這里調用上面dbcontextholder類的getdbtype()
方法獲取當前操作類別,同時可進行讀庫的負載均衡,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public class myabstractroutingdatasource extends abstractroutingdatasource { @value ( "${mysql.datasource.num}" ) private int num; private final logger log = loggerfactory.getlogger( this .getclass()); @override protected object determinecurrentlookupkey() { string typekey = dbcontextholder.getdbtype(); if (typekey == dbcontextholder.write) { log.info( "使用了寫庫" ); return typekey; } //使用隨機數決定使用哪個讀庫 int sum = numberutil.getrandom( 1 , num); log.info( "使用了讀庫{}" , sum); return dbcontextholder.read + sum; } } |
d、編寫配置類
由于要進行讀寫分離,不能再用springboot的默認配置,我們需要手動來進行配置。首先生成數據源,使用@configurproperties自動生成數據源:
1
2
3
4
5
6
7
8
9
10
11
12
|
/** * 寫數據源 * * @primary 標志這個 bean 如果在多個同類 bean 候選時,該 bean 優先被考慮。 * 多數據源配置的時候注意,必須要有一個主數據源,用 @primary 標志該 bean */ @primary @bean @configurationproperties (prefix = "mysql.datasource.write" ) public datasource writedatasource() { return new druiddatasource(); } |
讀數據源類似,注意有多少個讀庫就要設置多少個讀數據源,bean名為read+序號。
然后設置數據源,使用的是我們之前寫的myabstractroutingdatasource類
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** * 設置數據源路由,通過該類中的determinecurrentlookupkey決定使用哪個數據源 */ @bean public abstractroutingdatasource routingdatasource() { myabstractroutingdatasource proxy = new myabstractroutingdatasource(); map<object, object> targetdatasources = new hashmap<>( 2 ); targetdatasources.put(dbcontextholder.write, writedatasource()); targetdatasources.put(dbcontextholder.read+ "1" , read1()); proxy.setdefaulttargetdatasource(writedatasource()); proxy.settargetdatasources(targetdatasources); return proxy; } |
接著需要設置sqlsessionfactory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/** * 多數據源需要自己設置sqlsessionfactory */ @bean public sqlsessionfactory sqlsessionfactory() throws exception { sqlsessionfactorybean bean = new sqlsessionfactorybean(); bean.setdatasource(routingdatasource()); resourcepatternresolver resolver = new pathmatchingresourcepatternresolver(); // 實體類對應的位置 bean.settypealiasespackage(typealiasespackage); // mybatis的xml的配置 bean.setmapperlocations(resolver.getresources(mapperlocation)); bean.setconfiglocation(resolver.getresource(configlocation)); return bean.getobject(); } |
最后還得配置下事務,否則事務不生效
1
2
3
4
5
6
7
|
/** * 設置事務,事務需要知道當前使用的是哪個數據源才能進行事務處理 */ @bean public datasourcetransactionmanager datasourcetransactionmanager() { return new datasourcetransactionmanager(routingdatasource()); } |
4)、選擇數據源
多數據源配置好了,但是代碼層面如何選擇選擇數據源呢?這里介紹兩種辦法:
a、注解式
首先定義一個只讀注解,被這個注解方法使用讀庫,其他使用寫庫,如果項目是中途改造成讀寫分離可使用這個方法,無需修改業務代碼,只要在只讀的service方法上加一個注解即可。
1
2
3
4
|
@target ({elementtype.method,elementtype.type}) @retention (retentionpolicy.runtime) public @interface readonly { } |
然后寫一個切面來切換數據使用哪種數據源,重寫getorder保證本切面優先級高于事務切面優先級,在啟動類加上@enabletransactionmanagement(order = 10)
,為了代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@aspect @component public class readonlyinterceptor implements ordered { private static final logger log= loggerfactory.getlogger(readonlyinterceptor. class ); @around ( "@annotation(readonly)" ) public object setread(proceedingjoinpoint joinpoint,readonly readonly) throws throwable{ try { dbcontextholder.setdbtype(dbcontextholder.read); return joinpoint.proceed(); } finally { //清楚dbtype一方面為了避免內存泄漏,更重要的是避免對后續在本線程上執行的操作產生影響 dbcontextholder.cleardbtype(); log.info( "清除threadlocal" ); } } @override public int getorder() { return 0 ; } } |
b、方法名式
這種方法不許要注解,但是需要事務名稱按一定規則編寫,然后通過切面來設置數據庫類別,比如setxxx
設置為寫、getxxx
設置為讀,代碼我就不寫了,應該都知道怎么寫。
4、測試
編寫好代碼來試試結果如何,下面是運行截圖:
斷斷續續寫了好幾天終于是寫完了,,,如果有幫助到你,,歡迎star哦,,這里是完整代碼地址:點擊跳轉
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://www.cnblogs.com/wuyoucao/p/9610882.html