springBoot项目中配置双数据源 – 实现主从库的读写分离操作
首先先了解一下什么是读写分离?
读写分离其实就是将数据库分为了主从库,⼀个主库用于写数据,多个从库完成读数据的操作,主从库之间通过某种机制进行数据的同步,是⼀种常见的数据库架构。(⼀个主从同步集群,通常被称为是⼀个“分组”。)
数据库读写分离操作解决了什么问题呢?
大多数互联网业务,往往读多写少,这时候,数据库的读会首先成为数据库的瓶颈,这时,如果我们希望能够线性的提升数据库的读性能,消除读写锁冲突从而提升数据库的写性能,那么就可以使用“分组架构”(读写分离架构)。用⼀句话概括,读写分离是⽤来解决数据库读性能瓶颈的。
数据库读写分离需要注意的问题
在互联网的应用场景中,常常数据量大、并发量高、高可用要求高、⼀致性要求高,如果使用“读写分离”,就需要注意这些问题:
- 数据库连接池要进行区分,哪些是读连接池,哪些是写连接池,研发的难度会增加;
- 为了保证高可用,读连接池要能够实现故障自动转移;
- 主从的⼀致性问题需要考虑。
可以看到要考究的还是有很多的,所以相比于做缓存的复杂度,读写分离很多时候是作为缓存的⼀种补充方案。
本文读写分离实现方案
使用aop拦截业务层(service)的不同方法,对不同的方法改变sql调用时的数据源
代码实现
数据源枚举类
public enum DataSourceType
{
/**
* 主库
*/
MASTER,
/**
* 从库
*/
SLAVE
}
druid 配置属性 -> DruidProperties
@Configuration
public class DruidProperties {
@Value("${spring.datasource.druid.initialSize}")
private int initialSize;
@Value("${spring.datasource.druid.minIdle}")
private int minIdle;
@Value("${spring.datasource.druid.maxActive}")
private int maxActive;
@Value("${spring.datasource.druid.maxWait}")
private int maxWait;
@Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.druid.maxEvictableIdleTimeMillis}")
private int maxEvictableIdleTimeMillis;
@Value("${spring.datasource.druid.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.druid.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.druid.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.druid.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.druid.slave.enabled}")
public Boolean slaveEnable;
public DruidDataSource dataSource(DruidDataSource datasource) {
/** 配置初始化大小、最小、最大 */
datasource.setInitialSize(initialSize);
datasource.setMaxActive(maxActive);
datasource.setMinIdle(minIdle);
/** 配置获取连接等待超时的时间 */
datasource.setMaxWait(maxWait);
/** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
/** 配置一个连接在池中最小、最大生存的时间,单位是毫秒 */
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis);
/**
* 用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
*/
datasource.setValidationQuery(validationQuery);
/** 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 */
datasource.setTestWhileIdle(testWhileIdle);
/** 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */
datasource.setTestOnBorrow(testOnBorrow);
/** 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */
datasource.setTestOnReturn(testOnReturn);
return datasource;
}
}
yml文件如下配置:
# 数据源配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
druid:
# 主库数据源
master:
url: jdbc:mysql://114.98.231.178:3306/test_cloud?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: Sandzhi_321
# 从库数据源
slave:
#从数据源开关/默认关闭
enabled: false
url: jdbc:mysql://8.141.51.28:3306/ry_cloud_read?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: Sandzhi_321
# 初始连接数
initialSize: 5
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 5500
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一个连接在池中最大生存的时间,单位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置检测连接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# 设置白名单,不填则允许所有访问
allow:
url-pattern: /monitor/druid/*
filter:
stat:
enabled: true
# 慢SQL记录
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
数据源切换处理 -> DynamicDataSourceContextHolder
public class DynamicDataSourceContextHolder {
public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);
/**
* 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
* 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
*/
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
/**
* 设置数据源的变量
*/
public static void setDataSourceType(String dsType) {
log.info("切换到{}数据源", dsType);
CONTEXT_HOLDER.set(dsType);
}
/**
* 获得数据源的变量
*/
public static String getDataSourceType() {
return CONTEXT_HOLDER.get();
}
/**
* 清空数据源变量
*/
public static void clearDataSourceType() {
CONTEXT_HOLDER.remove();
}
}
动态数据源 -> DynamicDataSource
public class DynamicDataSource extends AbstractRoutingDataSource {
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
}
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}
druid 配置多数据源 -> DruidConfig
@Configuration
public class DruidConfig {
@Autowired
private DruidProperties druidProperties;
@Bean
@ConfigurationProperties("spring.datasource.druid.master")
public DataSource masterDataSource() {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean
@ConfigurationProperties("spring.datasource.druid.slave")
@ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
public DataSource slaveDataSource() {
DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(dataSource);
}
@Bean(name = "dynamicDataSource")
@Primary
public DynamicDataSource dataSource() {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource());
if (druidProperties.slaveEnable) {
targetDataSources.put(DataSourceType.SLAVE.name(), slaveDataSource());
}
return new DynamicDataSource(masterDataSource(), targetDataSources);
}
}
@ConditionalOnProperty注解:
通过@ConditionalOnProperty 控制配置类是否生效,可以将配置与代码进行分离,实现了更好的控制配置。@ConditionalOnProperty实现是通过havingValue与配置文件中的值对比,相同返回为true则配置类生效,反之失效。
注册aop处理 -> DataSourceAspect,实现不同方法执行sql切换数据源
/**
* 多数据源处理
*/
@Aspect
@Order(1)
@Component
public class DataSourceAspect {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private DruidProperties druidProperties;
//横切service层实现类所有方法
@Around("execution(* com.wisetorch..*ServiceImpl.*(..))")
public Object around(ProceedingJoinPoint point) throws Throwable {
if (!druidProperties.slaveEnable) {
return point.proceed();
}
// 获取到当前执行的方法名
String methodName = point.getSignature().getName();
if (isSlave(methodName)) {
// 标记为读库,可以自定义选择数据源
DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE.name());
} else {
// 标记为写库
DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER.name());
}
try {
return point.proceed();
} finally {
// 销毁数据源 在执行方法之后
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
/**
* 判断是否为读库
*
* @param methodName
* @return
*/
private boolean isSlave(String methodName) {
// 方法名以query、find、get开头的方法名走从库
return StringUtils.startsWithAny(methodName, new String[]{"query", "find", "get", "select"});
}
}
至此,项目中业务层的不同方法,会由于方法名的不同动态切换数据源。
spring实现原理 – AbstractRoutingDataSource
spring是通过AbstractRoutingDataSource抽象类实现多数据源动态切换的。如下是这个类的主要成员变量
// 是存储将要切换的多数据源信息,一般是<name,DataSource>
private Map<Object, Object> targetDataSources;
private Object defaultTargetDataSource;
private Map<Object, DataSource> resolvedDataSources;
private DataSource resolvedDefaultDataSource;
源码:
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
// 是存储将要切换的多数据源信息,一般是<name,DataSource>
private Map<Object, Object> targetDataSources;
private Object defaultTargetDataSource;
private Map<Object, DataSource> resolvedDataSources;
private DataSource resolvedDefaultDataSource;
}
---
public abstract class AbstractDataSource implements DataSource{}
从继承上看,AbstractRoutingDataSource继承AbstractDataSource。AbstractDataSource实现DataSource接口。那么AbstractRoutingDataSource就是一批DataSource实例的集合体。
操作数据库首先获取数据库连接Connection。AbstracRoutingDataSource通过实现DataSource接口getConnection来操作数据源。
1、AbstractRoutingDataSource的getConnection实现
public Connection getConnection() throws SQLException {
return this.determineTargetDataSource().getConnection();
}
2、实际是通过determineTargetDataSource去获取connection。determineTargetDataSource方法也很简单,通过lookupKey去resolvedDataSources中找到对应的数据源。如果没找到,就获取默认的dataSource。
protected DataSource determineTargetDataSource() {
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
Object lookupKey = this.determineCurrentLookupKey();
DataSource dataSource = (DataSource)this.resolvedDataSources.get(lookupKey);
if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
dataSource = this.resolvedDefaultDataSource;
}
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
} else {
return dataSource;
}
}
从方法实现中可以看出。是通过一个抽象方法:determineCurrentLookupKey获取需要lookupKey。这个抽象方法需要自定义类实现。(根据自己业务需求实现抽象方法)。
3、数据源怎么被放到resolvedDataSources中的呢?
AbstractRoutingDataSource实现了InitializingBean接口,重写了afterPropertiesSet()
public void afterPropertiesSet() {
if (this.targetDataSources == null) {
throw new IllegalArgumentException("Property 'targetDataSources' is required");
} else {
this.resolvedDataSources = new HashMap(this.targetDataSources.size());
// 1. 循环原有存储多数据源信息的targetDataSources
this.targetDataSources.forEach((key, value) -> {
// 2. 判断lookUpKey要不要重写,一般不用重写
Object lookupKey = this.resolveSpecifiedLookupKey(key);
// 3. 判断value是否Datasource对象,不是则生成DataSource对象,一般都是
DataSource dataSource = this.resolveSpecifiedDataSource(value);
// 4. 将魔改的<name,DataSource> 存入resolvedDataSources中备用
this.resolvedDataSources.put(lookupKey, dataSource);
});
//如果默认数据源不为空则指定对应数据源
if (this.defaultTargetDataSource != null) {
this.resolvedDefaultDataSource = this.resolveSpecifiedDataSource(this.defaultTargetDataSource);
}
}
}
afterPropertiesSet把targetDataSources中的DataSource做了加工和校验后放入了resolvedDataSources。defaultTargetDataSource也赋值给resolveDefaultDataSource。
因此,我们只需要将数据源集合和默认数据源通过AbstractRoutingDataSource提供的set方法放入targetDataSources和defaultTargetDataSource就可以实现动态数据源切换。
自定义类[DynamicDataSource]继承AbstractRoutingDataSource(见上述代码实现)
public class DynamicDataSource extends AbstractRoutingDataSource {
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
// 调用AbstractRoutingDataSource类里的set方法设置targetDataSources和defaultTargetDataSource
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
}
// 指定resolvedDataSources中的key,由此key可以通过resolvedDataSources属性的键来获取对应的DataSource数据源,
// 从而达到数据源切换的功能。
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceContextHolder.getDataSourceType();
}
}