本文介紹了Spring Boot + MyBatis讀寫分離,有需要了解Spring+MyBatis讀寫分離的朋友可參考。想了解更多相關資訊請持續關注我們應屆畢業生考試網!
其最終實現功能:
1.預設更新操作都使用寫資料來源
2.讀操作都使用slave資料來源
3.特殊設定:可以指定要使用的資料來源型別及名稱(如果有名稱,則會根據名稱使用相應的資料來源)
其實現原理如下:
1.通過Spring AOP對dao層介面進行攔截,並對需要指定資料來源的介面在ThradLocal中設定其資料來源型別及名稱
2.通過MyBatsi的外掛,對根據更新或者查詢操作在ThreadLocal中設定資料來源(dao層沒有指定的情況下)
3.繼承AbstractRoutingDataSource類。
在此直接寫死使用HikariCP作為資料來源
其實現步驟如下:
1.定義其資料來源配置檔案並進行解析為資料來源
2.定義AbstractRoutingDataSource類及其它註解
3.定義Aop攔截
4.定義MyBatis外掛
5.整合在一起
1.配置及解析類
其配置引數直接使用HikariCP的配置,其具體引數可以參考HikariCP。
在此使用yaml格式,名稱為,內容如下:
dds:
write:
jdbcUrl: jdbc:mysql://localhost:3306/order
password: liu123
username: root
maxPoolSize: 10
minIdle: 3
poolName: master
read:
- jdbcUrl: jdbc:mysql://localhost:3306/test
password: liu123
username: root
maxPoolSize: 10
minIdle: 3
poolName: slave1
- jdbcUrl: jdbc:mysql://localhost:3306/test2
password: liu123
username: root
maxPoolSize: 10
minIdle: 3
poolName: slave2
定義該配置所對應的Bean,名稱為DBConfig,內容如下:
@Component
@ConfigurationProperties(locations = "classpath:", prefix = "dds")
public class DBConfig {
private List<HikariConfig> read;
private HikariConfig write;
public List<HikariConfig> getRead() {
return read;
}
public void setRead(List<HikariConfig> read) {
= read;
}
public HikariConfig getWrite() {
return write;
}
public void setWrite(HikariConfig write) {
e = write;
}
}
把配置轉換為DataSource的工具類,名稱:DataSourceUtil,內容如下:
import riConfig;
import riDataSource;
import Source;
import yList;
import ;
public class DataSourceUtil {
public static DataSource getDataSource(HikariConfig config) {
return new HikariDataSource(config);
}
public static List<DataSource> getDataSource(List<HikariConfig> configs) {
List<DataSource> result = null;
if (configs != null && () > 0) {
result = new ArrayList<>(());
for (HikariConfig config : configs) {
(getDataSource(config));
}
} else {
result = new ArrayList<>(0);
}
return result;
}
}
2.註解及動態資料來源
定義註解@DataSource,其用於需要對個別方法指定其要使用的資料來源(如某個讀操作需要在master上執行,但另一讀方法b需要在讀資料來源的具體一臺上面執行)
@Retention(IME)
@Target(OD)
public @interface DataSource {
/**
* 型別,代表是使用讀還是寫
* @return
*/
DataSourceType type() default E;
/**
* 指定要使用的'DataSource的名稱
* @return
*/
String name() default "";
}
定義資料來源型別,分為兩種:READ,WRITE,內容如下:
public enum DataSourceType {
READ, WRITE;
}
定義儲存這此共享資訊的類DynamicDataSourceHolder,在其中定義了兩個ThreadLocal和一個map,holder用於儲存當前執行緒的資料來源型別(讀或者寫),pool用於儲存資料來源名稱(如果指定),其內容如下:
import ;
import urrentHashMap;
public class DynamicDataSourceHolder {
private static final Map<String, DataSourceType> cache = new ConcurrentHashMap<>();
private static final ThreadLocal<DataSourceType> holder = new ThreadLocal<>();
private static final ThreadLocal<String> pool = new ThreadLocal<>();
public static void putToCache(String key, DataSourceType dataSourceType) {
(key,dataSourceType);
}
public static DataSourceType getFromCach(String key) {
return (key);
}
public static void putDataSource(DataSourceType dataSourceType) {
(dataSourceType);
}
public static DataSourceType getDataSource() {
return ();
}
public static void putPoolName(String name) {
if (name != null && th() > 0) {
(name);
}
}
public static String getPoolName() {
return ();
}
public static void clearDataSource() {
ve();
ve();
}
}
動態資料來源類為DynamicDataSoruce,其繼承自AbstractRoutingDataSource,可以根據返回的key切換到相應的資料來源,其內容如下:
import riDataSource;
import ractRoutingDataSource;
import Source;
import Map;
import ;
import ;
import urrentHashMap;
import adLocalRandom;
public class DynamicDataSource extends AbstractRoutingDataSource {
private DataSource writeDataSource;
private List<DataSource> readDataSource;
private int readDataSourceSize;
private Map<String, String> dataSourceMapping = new ConcurrentHashMap<>();
@Override
public void afterPropertiesSet() {
if (eDataSource == null) {
throw new IllegalArgumentException("Property 'writeDataSource' is required");
}
setDefaultTargetDataSource(writeDataSource);
Map<Object, Object> targetDataSource = new HashMap<>();
((), writeDataSource);
String poolName = ((HikariDataSource)writeDataSource)oolName();
if (poolName != null && th() > 0) {
(poolName,());
}
if (DataSource == null) {
readDataSourceSize = 0;
} else {
for (int i = 0; i < (); i++) {
(() + i, (i));
poolName = ((HikariDataSource)(i))oolName();
if (poolName != null && th() > 0) {
(poolName,() + i);
}
}
readDataSourceSize = ();
}
setTargetDataSources(targetDataSource);
rPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey() {
DataSourceType dataSourceType = ataSource();
String dataSourceName = null;
if (dataSourceType == null ||dataSourceType == E || readDataSourceSize == 0) {
dataSourceName = ();
} else {
String poolName = oolName();
if (poolName == null) {
int idx = ent()Int(0, readDataSourceSize);
dataSourceName = () + idx;
} else {
dataSourceName = (poolName);
}
}
rDataSource();
return dataSourceName;
}
public void setWriteDataSource(DataSource writeDataSource) {
eDataSource = writeDataSource;
}
public void setReadDataSource(List<DataSource> readDataSource) {
DataSource = readDataSource;
}
}