网站首页 语言 会计 电脑 医学 资格证 职场 文艺体育 范文
当前位置:书香门第 > 计算机 > java语言

Spring+MyBatis数据读写分离的实例详解

栏目: java语言 / 发布于: / 人气:2.3W

本文介绍了Spring Boot + MyBatis读写分离,有需要了解Spring+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;

}

}