SpringBoot學習筆記之動態數據源切換

Springboot 動態數據源切換
1)、配置文件application.properties
# 更多數據源
custom.datasource.names=ds1,ds2
custom.datasource.ds1.driver-class-name=com.mysql.jdbc.Driver custom.datasource.ds1.url=jdbc:mysql://localhost:3306/ds1
custom.datasource.ds1.username=root
custom.datasource.ds1.password=123456
custom.datasource.ds2.driver-class-name=com.mysql.jdbc.Driver custom.datasource.ds2.url=jdbc:mysql://localhost:3306/ds2
custom.datasource.ds2.username=root
custom.datasource.ds2.password=123456

2)、配置文件中加上配置
#mybatis配置
mybatis.typeAliasesPackage=com.vk.liyj
#匹配mapper下的所有mapper.xml
#mybatis.mapperLocations=classpath:com/vk/liyj/mapper/*Mapper.xml
#匹配指定包下的所有mapper.xml
mybatis.mapperLocations=classpath*:com/vk/liyj/**/*Mapper.xml

3)、動態數據源切換相關代碼在dynamicDataSource包下
TargetDataSource爲我們自定義的annotation。
DynamicDataSourceRegister類爲數據源動態切換的核心類。該類實現了ImportBeanDefinitionRegistrar和EnvironmentAware這兩個接口,這兩個接口在系統啓動時被分別調用。這兩個接口的執行是有先後順序的,EnvironmentAware接口的setEnvironment方法會先被執行完成默認數據源和自定義數據源的初始化,然後再執行ImportBeanDefinitionRegistrar接口的registerBeanDefinitions方法完成默認數據源和目標數據源的註冊。
DynamicDataSourceContextHolder類中使用了ThreadLocal來保存當前線程使用的數據源,當前線程id是key,value是數據源名稱。dataSourceIds用於保存系統配置的數據源名稱。
DynamicDataSourceAspect是AOP類,主要完成前置和後置功能加強。該類中有兩個要注意的地方,@Aspect必須引用,表示這是一個AOP類,@Order(-1)表示該類要被AOP鏈式調用時優先被執行。
DynamicDataSource類繼承了AbstractRoutingDataSource類,在執行service方法調用之前被調用該方法獲取數據源。

4)、在SpringBootSampleApplication中啓動類註冊動態數據源
//註冊動態多數據源
@Import({DynamicDataSourceRegister.class})
//啓註解事務管理,等同於xml配置方式的 <tx:annotation-driven />
@EnableTransactionManagement

5)、在需要切換數據源的地方增加TargetDataSource註解,ds2就是我們配置在properties中的名字。Transactional表示該方法使用事務控制。
@Transactional
@TargetDataSource(name = "ds2")

5)、導入ds1,ds2數據庫腳本

6)、SpringBootTest 中的testDS1(),testDS2(),testDefaultDS(),testDefaultDSAdd()進行測試。

源碼下載地址:http://download.csdn.net/download/liyuejin/9986140

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章