前言
對于數據量在1千萬,單個mysql數據庫就可以支持,但是如果數據量大于這個數的時候,例如1億,那么查詢的性能就會很低。此時需要對數據庫做水平切分,常見的做法是按照用戶的賬號進行hash,然后選擇對應的數據庫。
最近公司項目需求,由于要兼容老系統的數據庫結構,需要搭建一個 可以動態切換、添加數據源的后端服務。
參考了過去的項目,通過配置多個sqlsessionfactory 來實現多數據源,這么做的話,未免過于笨重,而且無法實現動態添加數據源這個需求
通過 spring abstractroutingdatasource 為我們抽象了一個 dynamicdatasource 解決這一問題
簡單分析下 abstractroutingdatasource 的源碼
targetdatasources 就是我們的多個數據源,在初始化的時候會調用afterpropertiesset(),去解析我們的數據源 然后 put 到 resolveddatasources
實現了 datasource 的 getconnection(); 我們看看 determinetargetdatasource(); 做了什么
通過下面的 determinecurrentlookupkey();(這個方法需要我們實現) 返回一個key,然后從 resolveddatasources (其實也就是 targetdatasources) 中 get 一個數據源,實現了每次調用 getconnection(); 打開連接 切換數據源,如果想動態添加的話 只需要重新 set targetdatasources 再調用 afterpropertiesset() 即可
talk is cheap. show me the code
我使用的springboot版本為 1.5.x,下面是核心代碼
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
/** * 多數據源配置 * * @author taven * */ @configuration @mapperscan ( "com.gitee.taven.mapper" ) public class datasourceconfigurer { /** * datasource 自動配置并注冊 * * @return data source */ @bean ( "db0" ) @primary @configurationproperties (prefix = "datasource.db0" ) public datasource datasource0() { return druiddatasourcebuilder.create().build(); } /** * datasource 自動配置并注冊 * * @return data source */ @bean ( "db1" ) @configurationproperties (prefix = "datasource.db1" ) public datasource datasource1() { return druiddatasourcebuilder.create().build(); } /** * 注冊動態數據源 * * @return */ @bean ( "dynamicdatasource" ) public datasource dynamicdatasource() { dynamicroutingdatasource dynamicroutingdatasource = new dynamicroutingdatasource(); map<object, object> datasourcemap = new hashmap<>(); datasourcemap.put( "dynamic_db0" , datasource0()); datasourcemap.put( "dynamic_db1" , datasource1()); dynamicroutingdatasource.setdefaulttargetdatasource(datasource0()); // 設置默認數據源 dynamicroutingdatasource.settargetdatasources(datasourcemap); return dynamicroutingdatasource; } /** * sql session factory bean. * here to config datasource for sqlsessionfactory * <p> * you need to add @{@code @configurationproperties(prefix = "mybatis")}, if you are using *.xml file, * the {@code 'mybatis.type-aliases-package'} and {@code 'mybatis.mapper-locations'} should be set in * {@code 'application.properties'} file, or there will appear invalid bond statement exception * * @return the sql session factory bean */ @bean @configurationproperties (prefix = "mybatis" ) public sqlsessionfactorybean sqlsessionfactorybean() { sqlsessionfactorybean sqlsessionfactorybean = new sqlsessionfactorybean(); // 必須將動態數據源添加到 sqlsessionfactorybean sqlsessionfactorybean.setdatasource(dynamicdatasource()); return sqlsessionfactorybean; } /** * 事務管理器 * * @return the platform transaction manager */ @bean public platformtransactionmanager transactionmanager() { return new datasourcetransactionmanager(dynamicdatasource()); } } |
通過 threadlocal 獲取線程安全的數據源 key
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
33
34
35
36
|
package com.gitee.taven.config; public class dynamicdatasourcecontextholder { private static final threadlocal<string> contextholder = new threadlocal<string>() { @override protected string initialvalue() { return "dynamic_db0" ; } }; /** * to switch datasource * * @param key the key */ public static void setdatasourcekey(string key) { contextholder.set(key); } /** * get current datasource * * @return data source key */ public static string getdatasourcekey() { return contextholder.get(); } /** * to set datasource as default */ public static void cleardatasourcekey() { contextholder.remove(); } } |
動態 添加、切換數據源
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
/** * 動態數據源 * * @author taven * */ public class dynamicroutingdatasource extends abstractroutingdatasource { private final logger logger = loggerfactory.getlogger(getclass()); private static map<object, object> targetdatasources = new hashmap<>(); /** * 設置當前數據源 * * @return */ @override protected object determinecurrentlookupkey() { logger.info( "current datasource is [{}]" , dynamicdatasourcecontextholder.getdatasourcekey()); return dynamicdatasourcecontextholder.getdatasourcekey(); } @override public void settargetdatasources(map<object, object> targetdatasources) { super .settargetdatasources(targetdatasources); dynamicroutingdatasource.targetdatasources = targetdatasources; } /** * 是否存在當前key的 datasource * * @param key * @return 存在返回 true, 不存在返回 false */ public static boolean isexistdatasource(string key) { return targetdatasources.containskey(key); } /** * 動態增加數據源 * * @param map 數據源屬性 * @return */ public synchronized boolean adddatasource(map<string, string> map) { try { connection connection = null ; // 排除連接不上的錯誤 try { class .forname(map.get(druiddatasourcefactory.prop_driverclassname)); connection = drivermanager.getconnection( map.get(druiddatasourcefactory.prop_url), map.get(druiddatasourcefactory.prop_username), map.get(druiddatasourcefactory.prop_password)); system.out.println(connection.isclosed()); } catch (exception e) { return false ; } finally { if (connection != null && !connection.isclosed()) connection.close(); } string database = map.get( "database" ); //獲取要添加的數據庫名 if (stringutils.isblank(database)) return false ; if (dynamicroutingdatasource.isexistdatasource(database)) return true ; druiddatasource druiddatasource = (druiddatasource) druiddatasourcefactory.createdatasource(map); druiddatasource.init(); map<object, object> targetmap = dynamicroutingdatasource.targetdatasources; targetmap.put(database, druiddatasource); // 當前 targetdatasources 與 父類 targetdatasources 為同一對象 所以不需要set // this.settargetdatasources(targetmap); this .afterpropertiesset(); logger.info( "datasource {} has been added" , database); } catch (exception e) { logger.error(e.getmessage()); return false ; } return true ; } } |
可以通過 aop 或者 手動 dynamicdatasourcecontextholder.setdatasourcekey(string key) 切換數據源
需要注意的:當我們開啟了事務之后,是無法在去切換數據源的
本文項目源碼:https://gitee.com/yintianwen7/spring-dynamic-datasource
參考文獻:https://github.com/helloworlde/springboot-dynamicdatasource
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://www.jianshu.com/p/0a485c965b8b