在高并发下,需要对应用进行读写分离,配置多数据源,即写操作走主库,读操作则走从库,主从数据库负责各自的读和写,缓解了锁的争用,提高了读取性能。
实现读写分离有多种方式,如使用中间件MyCat、Sharding-JDBC等,这里我们使用Aop的方式在代码层面实现读写分离。
实现原理
实现读写分离,首先要对Mysql做主从复制,即搭建一个主数据库,以及一个或多个从数据库。
具体实现主从复制,可参照前一篇博客《基于docker配置MySQL主从复制》
使用Aop的方式,当调用业务层方法前,判断请求是否是只读操作,动态切换数据源,如果是只读操作,则切换从数据库的数据源,否则使用主数据库的数据源。
系统架构
🚀 项目仓库:KimTou/Open-LetFit: LetFit小程序后台开源版
这是我之前写的一个项目,具体代码可以在可以在上面我的GitHub仓库中找到,项目就是使用了本文章介绍的读写分离方式,感兴趣的同学可以作为参考。
代码实现
在application.yml配置MySQL
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
master:
username: root
password: 123456
url: jdbc:mysql://服务器ip:3306/letfit?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
driver-class-name: com.mysql.cj.jdbc.Driver
slave:
username: root
password: 123456
url: jdbc:mysql://服务器ip:3307/letfit?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
filters: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
创建 ReadOnly 注解
在业务层的方法上使用该注解,使用 ReadOnly 注解的方法只处理读操作,会切换到从机的数据源
package com.letfit.aop.annotation;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReadOnly {
}
创建枚举类
定义两个枚举类型 MASTER 、slave 分别代表数据库类型
package com.letfit.common;
public enum DBTypeEnum {
MASTER,
SLAVE;
}
编写动态切换数据源的工具类
package com.letfit.util;
@Slf4j
public class DynamicDbUtil {
private static final ThreadLocal<DBTypeEnum> CONTEXT_HAND = new ThreadLocal<>();
public static void set(DBTypeEnum dbTypeEnum){
CONTEXT_HAND.set(dbTypeEnum);
log.info("切换数据源:{}", dbTypeEnum);
}
public static void master(){
set(DBTypeEnum.MASTER);
}
public static void slave(){
set(DBTypeEnum.SLAVE);
}
public static void remove(){
CONTEXT_HAND.remove();
}
public static DBTypeEnum get(){
return CONTEXT_HAND.get();
}
}
编写 AbstractRoutingDataSource 的实现类
Spring boot提供了AbstractRoutingDataSource 根据用户定义的规则选择当前的数据源,这样我们可以在执行查询之前,设置使用的数据源。实现可动态路由的数据源,在每次数据库查询操作前执行。它的抽象方法 determineCurrentLookupKey() 决定使用哪个数据源。
AbstractRoutingDataSource 的部分源码如下
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
@Nullable
private Map<Object, Object> targetDataSources;
@Nullable
private Object defaultTargetDataSource;
@Nullable
private Map<Object, DataSource> resolvedDataSources;
@Nullable
private DataSource resolvedDefaultDataSource;
public AbstractRoutingDataSource() {
}
public void setTargetDataSources(Map<Object, Object> targetDataSources) {
this.targetDataSources = targetDataSources;
}
public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
this.defaultTargetDataSource = defaultTargetDataSource;
}
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;
}
}
@Nullable
protected abstract Object determineCurrentLookupKey();
}
编写 DynamicDataSource 继承 AbstractRoutingDataSource
package com.letfit.common;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDbUtil.get();
}
}
流程步骤:
1、重写数据源选择策略determineCurrentLookupKey()。
2、数据源配置类将数据源存放在AbstractRoutingDataSource的 targetDataSources和defaultTargetDataSource中,然后通过afterPropertiesSet()方法将数据源分别进行复制到resolvedDataSources和resolvedDefaultDataSource中。
3、进行数据库连接时,调用AbstractRoutingDataSource的getConnection()的方法,此时会先调用determineTargetDataSource()方法返回DataSource再进行getConnection()。
编写多数据源配置类
package com.letfit.config;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.letfit.common.DBTypeEnum;
import com.letfit.common.DynamicDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DataSourceConfig {
@ConfigurationProperties(prefix = "spring.datasource.master")
@Primary
@Bean
public DataSource masterDataSource(){
return DruidDataSourceBuilder.create().build();
}
@ConfigurationProperties(prefix = "spring.datasource.slave")
@Bean
public DataSource slaveDataSource(){
return DruidDataSourceBuilder.create().build();
}
@Bean
public DataSource targetDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slaveDataSource") DataSource slaveDataSource){
Map<Object,Object> targetDataSource = new HashMap<>(2);
targetDataSource.put(DBTypeEnum.MASTER, masterDataSource);
targetDataSource.put(DBTypeEnum.SLAVE, slaveDataSource);
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setTargetDataSources(targetDataSource);
dynamicDataSource.setDefaultTargetDataSource(masterDataSource);
return dynamicDataSource;
}
}
配置Mybatis
当我们只有一个数据源时,SpringBoot会默认配置Mybatis,现在我们有多个数据源,就需要手动配置Mybatis的SqlSessionFactory
package com.letfit.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Objects;
@Configuration
@EnableTransactionManagement
public class MybatisConfig {
@Resource(name = "targetDataSource")
private DataSource dataSource;
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
factoryBean.setTypeAliasesPackage("com.letfit.pojo");
Objects.requireNonNull(factoryBean.getObject()).getConfiguration().setMapUnderscoreToCamelCase(true);
return factoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager(){
return new DataSourceTransactionManager(dataSource);
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
配置Aop
package com.letfit.aop;
@Component
@Aspect
@Slf4j
public class DataSourceAop {
@Pointcut("@annotation(com.letfit.aop.annotation.ReadOnly)")
public void readPointcut(){}
@Before("readPointcut()")
public void readAdvise(){
log.info("切换数据源为从数据库");
DynamicDbUtil.slave();
}
}
业务层方法上使用 ReadOnly 注解
@ReadOnly
@Override
public ResultInfo<List<Source>> searchSource(String title) {
if(!ValiDateUtil.isLegalString(title)){
return ResultInfo.error(CodeEnum.PARAM_NOT_IDEAL, null);
}
List<Source> sourceList = sourceMapper.searchSource(title);
return ResultInfo.success(CodeEnum.SUCCESS, sourceList);
}
|