前言
開發(fā)中常用到主從數(shù)據(jù)庫(kù)來提高系統(tǒng)的性能。怎么樣才能方便的實(shí)現(xiàn)主從讀寫分離呢?近日工作任務(wù)較輕,有空學(xué)習(xí)學(xué)習(xí)技術(shù),遂來研究如果實(shí)現(xiàn)讀寫分離。這里用博客記錄下過程,一方面可備日后查看,同時(shí)也能分享給大家(網(wǎng)上的資料真的大都是抄來抄去,,還不帶格式的,看的真心難受)。
下面話不多說了,來一起看看詳細(xì)的介紹吧。
1、背景
一個(gè)項(xiàng)目中數(shù)據(jù)庫(kù)最基礎(chǔ)同時(shí)也是最主流的是單機(jī)數(shù)據(jù)庫(kù),讀寫都在一個(gè)庫(kù)中。當(dāng)用戶逐漸增多,單機(jī)數(shù)據(jù)庫(kù)無法滿足性能要求時(shí),就會(huì)進(jìn)行讀寫分離改造(適用于讀多寫少),寫操作一個(gè)庫(kù),讀操作多個(gè)庫(kù),通常會(huì)做一個(gè)數(shù)據(jù)庫(kù)集群,開啟主從備份,一主多從,以提高讀取性能。當(dāng)用戶更多讀寫分離也無法滿足時(shí),就需要分布式數(shù)據(jù)庫(kù)了(可能以后會(huì)學(xué)習(xí)怎么弄)。
正常情況下讀寫分離的實(shí)現(xiàn),首先要做一個(gè)一主多從的數(shù)據(jù)庫(kù)集群,同時(shí)還需要進(jìn)行數(shù)據(jù)同步。這一篇記錄如何用mysql搭建一個(gè)一主多次的配置,下一篇記錄代碼層面如何實(shí)現(xiàn)讀寫分離。
2、搭建一主多從數(shù)據(jù)庫(kù)集群
主從備份需要多臺(tái)虛擬機(jī),我是用wmware完整克隆多個(gè)實(shí)例,注意直接克隆的虛擬機(jī)會(huì)導(dǎo)致每個(gè)數(shù)據(jù)庫(kù)的uuid相同,需要修改為不同的uuid。修改方法參考這個(gè):點(diǎn)擊跳轉(zhuǎn)。
主庫(kù)配置
主數(shù)據(jù)庫(kù)(master)中新建一個(gè)用戶用于從數(shù)據(jù)庫(kù)(slave)讀取主數(shù)據(jù)庫(kù)二進(jìn)制日志,sql語句如下:
1
2
3
|
mysql> create user 'repl' @ '%' identified by '123456' ;#創(chuàng)建用戶 mysql> grant replication slave on *.* to 'repl' @ '%' ;#分配權(quán)限 mysql>flush privileges; #刷新權(quán)限 |
同時(shí)修改mysql配置文件開啟二進(jìn)制日志,新增部分如下:
1
2
3
4
|
[mysqld] server-id= 1 log-bin=master-bin log-bin-index=master-bin.index |
然后重啟數(shù)據(jù)庫(kù),使用show master status;
語句查看主庫(kù)狀態(tài),如下所示:
從庫(kù)配置
同樣先新增幾行配置:
1
2
3
4
|
[mysqld] server-id= 2 relay-log-index=slave-relay-bin.index relay-log=slave-relay-bin |
然后重啟數(shù)據(jù)庫(kù),使用如下語句連接主庫(kù):
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 ; |
接著運(yùn)行start slave;
開啟備份,正常情況如下圖所示:slave_io_running和slave_sql_running都為yes。
可以用這個(gè)步驟開啟多個(gè)從庫(kù)。
默認(rèn)情況下備份是主庫(kù)的全部操作都會(huì)備份到從庫(kù),實(shí)際可能需要忽略某些庫(kù),可以在主庫(kù)中增加如下配置:
1
2
3
4
5
6
7
|
# 不同步哪些數(shù)據(jù)庫(kù) binlog-ignore-db = mysql binlog-ignore-db = test binlog-ignore-db = information_schema # 只同步哪些數(shù)據(jù)庫(kù),除此之外,其他不同步 binlog- do -db = game |
3、代碼層面進(jìn)行讀寫分離
代碼環(huán)境是springboot+mybatis+druib連接池。想要讀寫分離就需要配置多個(gè)數(shù)據(jù)源,在進(jìn)行寫操作是選擇寫的數(shù)據(jù)源,讀操作時(shí)選擇讀的數(shù)據(jù)源。其中有兩個(gè)關(guān)鍵點(diǎn):
- 如何切換數(shù)據(jù)源
- 如何根據(jù)不同的方法選擇正確的數(shù)據(jù)源
1)、如何切換數(shù)據(jù)源
通常用springboot時(shí)都是使用它的默認(rèn)配置,只需要在配置文件中定義好連接屬性就行了,但是現(xiàn)在我們需要自己來配置了,spring是支持多數(shù)據(jù)源的,多個(gè)datasource放在一個(gè)hashmaptargetdatasource中,通過derterminecurrentlookupkey獲取key來覺定要使用哪個(gè)數(shù)據(jù)源。因此我們的目標(biāo)就很明確了,建立多個(gè)datasource放到targetdatasource中,同時(shí)重寫derterminecurrentlookupkey方法來決定使用哪個(gè)key。
2)、如何選擇數(shù)據(jù)源
事務(wù)一般是注解在service層的,因此在開始這個(gè)service方法調(diào)用時(shí)要確定數(shù)據(jù)源,有什么通用方法能夠在開始執(zhí)行一個(gè)方法前做操作呢?相信你已經(jīng)想到了那就是切面 。怎么切有兩種辦法:
- 注解式,定義一個(gè)只讀注解,被該數(shù)據(jù)標(biāo)注的方法使用讀庫(kù)
- 方法名,根據(jù)方法名寫切點(diǎn),比如getxxx用讀庫(kù),setxxx用寫庫(kù)
3)、代碼編寫
a、編寫配置文件,配置兩個(gè)數(shù)據(jù)源信息
只有必填信息,其他都有默認(rèn)設(shè)置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
mysql: datasource: #讀庫(kù)數(shù)目 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類
這個(gè)類用來設(shè)置數(shù)據(jù)庫(kù)類別,其中有一個(gè)threadlocal用來保存每個(gè)線程的是使用讀庫(kù),還是寫庫(kù)。代碼如下:
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保存當(dāng)前線程是否處于讀模式(通過開始read_only注解在開始操作前設(shè)置模式為讀模式, * 操作結(jié)束后清除該數(shù)據(jù),避免內(nèi)存泄漏,同時(shí)也為了后續(xù)在該線程進(jìn)行寫操作時(shí)任然為讀模式 * @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( "設(shè)置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在開始進(jìn)行數(shù)據(jù)庫(kù)操作時(shí)會(huì)通過這個(gè)方法來決定使用哪個(gè)數(shù)據(jù)庫(kù),因此我們?cè)谶@里調(diào)用上面dbcontextholder類的getdbtype()
方法獲取當(dāng)前操作類別,同時(shí)可進(jìn)行讀庫(kù)的負(fù)載均衡,代碼如下:
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( "使用了寫庫(kù)" ); return typekey; } //使用隨機(jī)數(shù)決定使用哪個(gè)讀庫(kù) int sum = numberutil.getrandom( 1 , num); log.info( "使用了讀庫(kù){}" , sum); return dbcontextholder.read + sum; } } |
d、編寫配置類
由于要進(jìn)行讀寫分離,不能再用springboot的默認(rèn)配置,我們需要手動(dòng)來進(jìn)行配置。首先生成數(shù)據(jù)源,使用@configurproperties自動(dòng)生成數(shù)據(jù)源:
1
2
3
4
5
6
7
8
9
10
11
12
|
/** * 寫數(shù)據(jù)源 * * @primary 標(biāo)志這個(gè) bean 如果在多個(gè)同類 bean 候選時(shí),該 bean 優(yōu)先被考慮。 * 多數(shù)據(jù)源配置的時(shí)候注意,必須要有一個(gè)主數(shù)據(jù)源,用 @primary 標(biāo)志該 bean */ @primary @bean @configurationproperties (prefix = "mysql.datasource.write" ) public datasource writedatasource() { return new druiddatasource(); } |
讀數(shù)據(jù)源類似,注意有多少個(gè)讀庫(kù)就要設(shè)置多少個(gè)讀數(shù)據(jù)源,bean名為read+序號(hào)。
然后設(shè)置數(shù)據(jù)源,使用的是我們之前寫的myabstractroutingdatasource類
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** * 設(shè)置數(shù)據(jù)源路由,通過該類中的determinecurrentlookupkey決定使用哪個(gè)數(shù)據(jù)源 */ @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; } |
接著需要設(shè)置sqlsessionfactory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/** * 多數(shù)據(jù)源需要自己設(shè)置sqlsessionfactory */ @bean public sqlsessionfactory sqlsessionfactory() throws exception { sqlsessionfactorybean bean = new sqlsessionfactorybean(); bean.setdatasource(routingdatasource()); resourcepatternresolver resolver = new pathmatchingresourcepatternresolver(); // 實(shí)體類對(duì)應(yīng)的位置 bean.settypealiasespackage(typealiasespackage); // mybatis的xml的配置 bean.setmapperlocations(resolver.getresources(mapperlocation)); bean.setconfiglocation(resolver.getresource(configlocation)); return bean.getobject(); } |
最后還得配置下事務(wù),否則事務(wù)不生效
1
2
3
4
5
6
7
|
/** * 設(shè)置事務(wù),事務(wù)需要知道當(dāng)前使用的是哪個(gè)數(shù)據(jù)源才能進(jìn)行事務(wù)處理 */ @bean public datasourcetransactionmanager datasourcetransactionmanager() { return new datasourcetransactionmanager(routingdatasource()); } |
4)、選擇數(shù)據(jù)源
多數(shù)據(jù)源配置好了,但是代碼層面如何選擇選擇數(shù)據(jù)源呢?這里介紹兩種辦法:
a、注解式
首先定義一個(gè)只讀注解,被這個(gè)注解方法使用讀庫(kù),其他使用寫庫(kù),如果項(xiàng)目是中途改造成讀寫分離可使用這個(gè)方法,無需修改業(yè)務(wù)代碼,只要在只讀的service方法上加一個(gè)注解即可。
1
2
3
4
|
@target ({elementtype.method,elementtype.type}) @retention (retentionpolicy.runtime) public @interface readonly { } |
然后寫一個(gè)切面來切換數(shù)據(jù)使用哪種數(shù)據(jù)源,重寫getorder保證本切面優(yōu)先級(jí)高于事務(wù)切面優(yōu)先級(jí),在啟動(dòng)類加上@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一方面為了避免內(nèi)存泄漏,更重要的是避免對(duì)后續(xù)在本線程上執(zhí)行的操作產(chǎn)生影響 dbcontextholder.cleardbtype(); log.info( "清除threadlocal" ); } } @override public int getorder() { return 0 ; } } |
b、方法名式
這種方法不許要注解,但是需要事務(wù)名稱按一定規(guī)則編寫,然后通過切面來設(shè)置數(shù)據(jù)庫(kù)類別,比如setxxx
設(shè)置為寫、getxxx
設(shè)置為讀,代碼我就不寫了,應(yīng)該都知道怎么寫。
4、測(cè)試
編寫好代碼來試試結(jié)果如何,下面是運(yùn)行截圖:
斷斷續(xù)續(xù)寫了好幾天終于是寫完了,,,如果有幫助到你,,歡迎star哦,,這里是完整代碼地址:點(diǎn)擊跳轉(zhuǎn)
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)服務(wù)器之家的支持。
原文鏈接:http://www.cnblogs.com/wuyoucao/p/9610882.html