3.1、原理介紹
3.2、**示例a、配置檔案
spring.aop.proxy-target-class = true
spring.aop.auto = true
spring.datasource.druid.db1.url =
spring.datasource.druid.db1.username =
spring.datasource.druid.db1.password =
spring.datasource.druid.db1.driver-class-name = com.mysql.jdbc.driver
spring.datasource.druid.db1.initialsize = 5
spring.datasource.druid.db1.minidle = 5
spring.datasource.druid.db1.maxactive = 20
spring.datasource.druid.db2.url =
spring.datasource.druid.db2.username =
spring.datasource.druid.db2.password =
spring.datasource.druid.db2.driver-class-name = com.mysql.jdbc.driver
spring.datasource.druid.db2.initialsize = 5
spring.datasource.druid.db2.minidle = 5
spring.datasource.druid.db2.maxactive = 20
spring.datasource.druid.db3.url =
spring.datasource.druid.db3.username =
spring.datasource.druid.db3.password =
spring.datasource.druid.db3.driver-class-name = com.mysql.jdbc.driver
spring.datasource.druid.db3.initialsize = 5
spring.datasource.druid.db3.minidle = 5
spring.datasource.druid.db3.maxactive = 20
b、生成datasource@bean(name = "db1")
@configurationproperties(prefix = "spring.datasource.druid.db1")
public datasource db1()
@bean(name = "db2")
@configurationproperties(prefix = "spring.datasource.druid.db2")
public datasource db2()
@bean(name = "db3")
@configurationproperties(prefix = "spring.datasource.druid.db3")
public datasource db3()
c、定義資料源的key@getter
@allargsconstructor
public enum dbtypeenum
d、構造資料來源和sessionfactory/**
* 動態資料來源配置
** @return
*/@bean
@primary
public datasource multipledatasource(
@qualifier("db1") datasource db1,
@qualifier("db2") datasource db2,
@qualifier("db3") datasource db3)
@bean("sqlsessionfactory")
public sqlsessionfactory sqlsessionfactory() throws exception );
sqlsessionfactory.setglobalconfig(globalconfiguration());
return sqlsessionfactory.getobject();
}
e、重寫datasource切換策略public class dynamicdatasource extends abstractroutingdatasource
}
f、儲存資料來源切換的上下文資訊public class dbcontextholder
/*** 取得當前資料來源
** @return
*/public static string getdbtype()
/** 清除上下文資料 */
public static void cleardbtype()
}
g、aop實現動態的資料來源切換@component
@order(value = -100)
@slf4j
@aspect
public class datasourceswitchaspect
private void db2aspect() {}
private void db3aspect() {}
@before("db1aspect()")
public void db1()
@before("db2aspect()")
public void db2()
@before("db3aspect()")
public void db3()
}
輕鬆實現SpringBoot實現多資料來源與事物處理
歡迎進入我的部落格,樂於分享是一種美德 首先啟動類所在的包一定要放在其他的類的父包中,這樣容易讓啟動類掃瞄到其他的類,不需要多餘的配置了 事物管理 事物原理 事物分類 單事物處理 單資料來源 同乙個專案 連線乙個資料庫 直接在需要加註解的方法 上面加上乙個註解 transactional 類 ind...
SpringBoot實現多資料來源配置
spring.datasource primary url jdbc mysql localhost 3306 test1 spring.datasource primary username root spring.datasource primary password root spring.d...
Spring Boot多資料來源配置
方案實現 新建兩個配置類 即加 configuration註解的類 乙個為primarydatasourceconfig,用來配置本專案的資料來源 另乙個叫seconddatasourceconfig,用來配置需要同步的資料來源。如下 configuration public class prima...