Spring Boot + Mybatis多數(shù)據(jù)源和動(dòng)態(tài)數(shù)據(jù)源配置方法
網(wǎng)上的文章基本上都是只有多數(shù)據(jù)源或只有動(dòng)態(tài)數(shù)據(jù)源,而最近的項(xiàng)目需要同時(shí)使用兩種方式,記錄一下配置方法供大家參考。
應(yīng)用場景
項(xiàng)目需要同時(shí)連接兩個(gè)不同的數(shù)據(jù)庫A, B,并且它們都為主從架構(gòu),一臺(tái)寫庫,多臺(tái)讀庫。
多數(shù)據(jù)源
首先要將spring boot自帶的DataSourceAutoConfiguration禁掉,因?yàn)樗鼤?huì)讀取application.properties文件的spring.datasource.*屬性并自動(dòng)配置單數(shù)據(jù)源。在@SpringBootApplication注解中添加exclude屬性即可:
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class
})
public class TitanWebApplication {
public static void main(String[] args) {
SpringApplication.run(TitanWebApplication.class, args);
}
}
然后在application.properties中配置多數(shù)據(jù)源連接信息:
# titan庫 spring.datasource.titan-master.url=jdbc:mysql://X.X.X.X:port/titan?characterEncoding=UTF-8 spring.datasource.titan-master.username= spring.datasource.titan-master.password= spring.datasource.titan-master.driver-class-name=com.mysql.jdbc.Driver # 連接池配置 # 省略 # 其它庫 spring.datasource.db2.url=jdbc:mysql://X.X.X.X:port/titan2?characterEncoding=UTF-8 spring.datasource.db2.username= spring.datasource.db2.password= spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver
由于我們禁掉了自動(dòng)數(shù)據(jù)源配置,因些下一步就需要手動(dòng)將這些數(shù)據(jù)源創(chuàng)建出來:
@Configuration
public class DataSourceConfig {
@Bean(name = "titanMasterDS")
@ConfigurationProperties(prefix = "spring.datasource.titan-master") // application.properteis中對應(yīng)屬性的前綴
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "ds2")
@ConfigurationProperties(prefix = "spring.datasource.db2") // application.properteis中對應(yīng)屬性的前綴
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
}
接下來需要配置兩個(gè)mybatis的SqlSessionFactory分別使用不同的數(shù)據(jù)源:
@Configuration
@MapperScan(basePackages = {"titan.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory1")
public class MybatisDbAConfig {
@Autowired
@Qualifier("titanMasterDS")
private DataSource ds1;
@Bean
public SqlSessionFactory sqlSessionFactory1() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(ds1); // 使用titan數(shù)據(jù)源, 連接titan庫
return factoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1()); // 使用上面配置的Factory
return template;
}
}
經(jīng)過上面的配置后,titan.mapper下的Mapper接口,都會(huì)使用titan數(shù)據(jù)源。同理可配第二個(gè)SqlSessionFactory:
@Configuration
@MapperScan(basePackages = {"other.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory2")
public class MybatisDbBConfig {
@Autowired
@Qualifier("ds2")
private DataSource ds2;
@Bean
public SqlSessionFactory sqlSessionFactory2() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(ds2);
return factoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2());
return template;
}
}
完成這些配置后,假設(shè)有2個(gè)Mapper titan.mapper.UserMapper和other.mapper.RoleMapper,使用前者時(shí)會(huì)自動(dòng)連接titan庫,后者連接ds2庫。
動(dòng)態(tài)數(shù)據(jù)源
使用動(dòng)態(tài)數(shù)據(jù)源的初衷,是能在應(yīng)用層做到讀寫分離,即在程序代碼中控制不同的查詢方法去連接不同的庫。除了這種方法以外,數(shù)據(jù)庫中間件也是個(gè)不錯(cuò)的選擇,它的優(yōu)點(diǎn)是數(shù)據(jù)庫集群對應(yīng)用來說只暴露為單庫,不需要切換數(shù)據(jù)源的代碼邏輯。
我們通過自定義注解 + AOP的方式實(shí)現(xiàn)數(shù)據(jù)源動(dòng)態(tài)切換。
首先定義一個(gè)ContextHolder, 用于保存當(dāng)前線程使用的數(shù)據(jù)源名:
public class DataSourceContextHolder {
public static final Logger log = LoggerFactory.getLogger(DataSourceContextHolder.class);
/**
* 默認(rèn)數(shù)據(jù)源
*/
public static final String DEFAULT_DS = "titan-master";
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
// 設(shè)置數(shù)據(jù)源名
public static void setDB(String dbType) {
log.debug("切換到{}數(shù)據(jù)源", dbType);
contextHolder.set(dbType);
}
// 獲取數(shù)據(jù)源名
public static String getDB() {
return (contextHolder.get());
}
// 清除數(shù)據(jù)源名
public static void clearDB() {
contextHolder.remove();
}
}
然后自定義一個(gè)javax.sql.DataSource接口的實(shí)現(xiàn),這里只需要繼承Spring為我們預(yù)先實(shí)現(xiàn)好的父類AbstractRoutingDataSource即可:
public class DynamicDataSource extends AbstractRoutingDataSource {
private static final Logger log = LoggerFactory.getLogger(DynamicDataSource.class);
@Override
protected Object determineCurrentLookupKey() {
log.debug("數(shù)據(jù)源為{}", DataSourceContextHolder.getDB());
return DataSourceContextHolder.getDB();
}
}
創(chuàng)建動(dòng)態(tài)數(shù)據(jù)源:
/**
* 動(dòng)態(tài)數(shù)據(jù)源: 通過AOP在不同數(shù)據(jù)源之間動(dòng)態(tài)切換
* @return
*/
@Bean(name = "dynamicDS1")
public DataSource dataSource() {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
// 默認(rèn)數(shù)據(jù)源
dynamicDataSource.setDefaultTargetDataSource(dataSource1());
// 配置多數(shù)據(jù)源
Map<Object, Object> dsMap = new HashMap(5);
dsMap.put("titan-master", dataSource1());
dsMap.put("ds2", dataSource2());
dynamicDataSource.setTargetDataSources(dsMap);
return dynamicDataSource;
}
自定義注釋@DS用于在編碼時(shí)指定方法使用哪個(gè)數(shù)據(jù)源:
@Retention(RetentionPolicy.RUNTIME)
@Target({
ElementType.METHOD
})
public @interface DS {
String value() default "titan-master";
}
編寫AOP切面,實(shí)現(xiàn)切換邏輯:
@Aspect
@Component
public class DynamicDataSourceAspect {
@Before("@annotation(DS)")
public void beforeSwitchDS(JoinPoint point){
//獲得當(dāng)前訪問的class
Class<?> className = point.getTarget().getClass();
//獲得訪問的方法名
String methodName = point.getSignature().getName();
//得到方法的參數(shù)的類型
Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
String dataSource = DataSourceContextHolder.DEFAULT_DS;
try {
// 得到訪問的方法對象
Method method = className.getMethod(methodName, argClass);
// 判斷是否存在@DS注解
if (method.isAnnotationPresent(DS.class)) {
DS annotation = method.getAnnotation(DS.class);
// 取出注解中的數(shù)據(jù)源名
dataSource = annotation.value();
}
} catch (Exception e) {
e.printStackTrace();
}
// 切換數(shù)據(jù)源
DataSourceContextHolder.setDB(dataSource);
}
@After("@annotation(DS)")
public void afterSwitchDS(JoinPoint point){
DataSourceContextHolder.clearDB();
}
}
完成上述配置后,在先前SqlSessionFactory配置中指定使用DynamicDataSource就可以在Service中愉快的切換數(shù)據(jù)源了:
@Autowired
private UserAModelMapper userAMapper;
@DS("titan-master")
public String ds1() {
return userAMapper.selectByPrimaryKey(1).getName();
}
@DS("ds2")
public String ds2() {
return userAMapper.selectByPrimaryKey(1).getName();
}
總結(jié)
以上所述是小編給大家介紹的Spring Boot + Mybatis多數(shù)據(jù)源和動(dòng)態(tài)數(shù)據(jù)源配置方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- Spring Boot 動(dòng)態(tài)數(shù)據(jù)源示例(多數(shù)據(jù)源自動(dòng)切換)
- 詳解Spring Boot + Mybatis 實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)源
- SpringBoot實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)源切換的項(xiàng)目實(shí)踐
- SpringBoot配置動(dòng)態(tài)數(shù)據(jù)源的實(shí)戰(zhàn)詳解
- SpringBoot動(dòng)態(tài)數(shù)據(jù)源連接測試的操作詳解
- SpringBoot實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)源切換的方法總結(jié)
- Spring Boot 動(dòng)態(tài)數(shù)據(jù)源在事務(wù)中切庫失效問題排查
相關(guān)文章
Java基礎(chǔ)之線程鎖相關(guān)知識(shí)總結(jié)
今天給大家?guī)淼氖顷P(guān)于Java線程的相關(guān)知識(shí),文章圍繞著Java線程鎖展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
Springboot基于assembly的服務(wù)化打包方案及spring boot部署方式
這篇文章主要介紹了Springboot基于assembly的服務(wù)化打包方案及springboot項(xiàng)目的幾種常見的部署方式,本文主要針對第二種部署方式提供一種更加友好的打包方案,需要的朋友可以參考下2017-12-12
java前后端加密解密crypto-js的實(shí)現(xiàn)
這篇文章主要介紹了java前后端加密解密crypto-js的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
Java8默認(rèn)方法Default Methods原理及實(shí)例詳解
這篇文章主要介紹了Java8默認(rèn)方法Default Methods原理及實(shí)例詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01
springMVC幾種頁面跳轉(zhuǎn)方式小結(jié)
本篇文章主要介紹了springMVC 幾種頁面跳轉(zhuǎn)方式,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02
Spring?Native打包本地鏡像的操作方法(無需通過Graal的maven插件buildtools)
這篇文章主要介紹了Spring?Native打包本地鏡像,無需通過Graal的maven插件buildtools,本文探索一下,如果不通過這個(gè)插件來生成鏡像,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
spring boot中xalan引入報(bào)錯(cuò)系統(tǒng)找不到指定的文件原因分析
這篇文章主要介紹了spring boot中xalan引入報(bào)錯(cuò)系統(tǒng)找不到指定的文件,主要原因是內(nèi)嵌的tomcat9.0.36,本文給大家分享最新解決方法,需要的朋友可以參考下2023-08-08
Maven項(xiàng)目讀取resources文件路徑問題解決方案
這篇文章主要介紹了Maven項(xiàng)目讀取resources文件路徑問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09

