一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|JavaScript|易語言|

服務器之家 - 編程語言 - Java教程 - spring實現動態切換、添加數據源及源碼分析

spring實現動態切換、添加數據源及源碼分析

2021-05-31 13:37殷天文 Java教程

這篇文章主要給大家介紹了關于spring實現動態切換、添加數據源及源碼分析的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前言

對于數據量在1千萬,單個mysql數據庫就可以支持,但是如果數據量大于這個數的時候,例如1億,那么查詢的性能就會很低。此時需要對數據庫做水平切分,常見的做法是按照用戶的賬號進行hash,然后選擇對應的數據庫。

最近公司項目需求,由于要兼容老系統的數據庫結構,需要搭建一個 可以動態切換、添加數據源的后端服務。

參考了過去的項目,通過配置多個sqlsessionfactory 來實現多數據源,這么做的話,未免過于笨重,而且無法實現動態添加數據源這個需求

spring實現動態切換、添加數據源及源碼分析

通過 spring abstractroutingdatasource 為我們抽象了一個 dynamicdatasource 解決這一問題

spring實現動態切換、添加數據源及源碼分析

簡單分析下 abstractroutingdatasource 的源碼

spring實現動態切換、添加數據源及源碼分析

spring實現動態切換、添加數據源及源碼分析

targetdatasources 就是我們的多個數據源,在初始化的時候會調用afterpropertiesset(),去解析我們的數據源 然后 put 到 resolveddatasources

spring實現動態切換、添加數據源及源碼分析

實現了 datasource 的 getconnection(); 我們看看 determinetargetdatasource(); 做了什么

spring實現動態切換、添加數據源及源碼分析

通過下面的 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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产精品久久久久久搜索 | 扒开双腿疯狂进出爽爽动态图 | 国内精品中文字幕 | 国模孕妇季玥全部人体写真 | 色导行| 色老板视频在线观看 | 星星动漫在线观看无删减 | 2021福利视频| 亚洲国产AV一区二区三区四区 | 视频一区二区三区在线观看 | 欧美日韩国产在线人成dvd | 办公室操秘书 | 亚洲精品在线看 | 国产免费一区不卡在线 | 动漫美女强行被吸乳做羞羞事 | 娇妻中日久久持久久 | 久久成人永久免费播放 | 三级欧美在线 | 亚洲国产欧美在线看片 | 性free非洲老妇 | 国产精品青青在线观看香蕉 | 午夜 在线播放 | 91精品国产综合久 | 法国老妇性xx在线播放 | 精品国产综合区久久久久久 | 成人资源影音先锋久久资源网 | 男女男精品网站 | 91精品国产亚洲爽啪在线影院 | 嫩模被黑人粗大挺进 | 51香蕉视频| caoporn国产 | 色就色欧美综合偷拍区a | 国产成人一区二区三区影院免费 | 久久爽狠狠添AV激情五月 | 久久亚洲精品AV成人无 | 精品久久成人免费第三区 | 国产精品免费_区二区三区观看 | 欧美乱子伦xxxx12在线 | 国产精品美女久久久久网站 | 美女脱了内裤打开腿让男人图片 | 亚洲免费小视频 |