SpringBoot+MyBatisPlus实现读写分离

1、前言

随着业务量的不断增长,数据库的读写压力也越来越大。为了解决这个问题,我们可以采用读写分离的方案来分担数据库的读写负载。本文将介绍如何使用 Spring Boot + MyBatis Plus + MySQL 实现读写分离。

2、读写分离原理

读写分离是指将数据库的读操作和写操作分别放到不同的数据库实例上,从而达到分担数据库负载的目的。一般情况下,写操作的频率比读操作高,因此可以将写操作放到主库上,将读操作放到从库上。这样可以保证主库的写入性能,同时也可以提高从库的读取性能。

3、实现步骤

3.1. 主从复制搭建

首先,我们需要创建两个数据库实例,一个用于主库,一个用于从库。这里我们使用 MySQL 数据库作为示例。

参见搭建mysql主从复制一文。

3.2.配置pom.xml

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	</dependency>
<!-- 连接池 -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-starter</artifactId>
	<version>1.1.9</version>
</dependency>
<!--aop -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
	<groupId>org.aspectj</groupId>
	<artifactId>aspectjtools</artifactId>
	<version>1.8.13</version>
</dependency>

3.3. 配置数据源

在 Spring Boot 中,我们可以使用 application.yml 文件来配置数据源。在这里,我们需要配置两个数据源,一个用于主库,一个用于从库。具体配置如下:

mysql:
  datasource:
    readNum: 1
    type: com.alibaba.druid.pool.DruidDataSource
    write:
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://10.10.26.212:3306/test?useSSL=false&useUnicode=true
      minIdle: 5
      maxActive: 100
      initialSize: 10
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 'x'
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 50
      removeAbandoned: true
      filters: stat
    read1:
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://10.10.26.213:3306/test?useSSL=false&useUnicode=true
      minIdle: 5
      maxActive: 100
      initialSize: 10
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 'x'
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 50
      removeAbandoned: true
      filters: stat

3.4. 配置 MyBatis Plus

MyBatis Plus 是一个 MyBatis 的增强工具,它可以简化 MyBatis 的开发流程。在这里,我们需要在 application.yml 文件中配置 MyBatis Plus 的相关参数。具体配置如下:

mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
  typeAliasesPackage: com.sandy.dyds.model

3.5. 实现读写分离

首先,我们需要创建一个 DbContextHolder 类,用于保存当前线程使用的数据源。具体实现如下:

@Log4j2
public class DbContextHolder {
    public static final String WRITE = "write";
    public static final String READ = "read";
    private static ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public static void setDbType(String dbType) {
        if(dbType == null) {
            throw new NullPointerException();
        }
        contextHolder.set(dbType);
    }

    public static String getDbType() {
        return contextHolder.get() == null ? WRITE : contextHolder.get();
    }

    public static void clearDbType() {
        contextHolder.remove();
    }
}

然后,我们需要创建一个 RoutingDataSource 类,用于动态切换数据源。具体实现如下:

@Log4j2
public class RoutingDataSource extends AbstractRoutingDataSource {

    @Value("${mysql.datasource.readNum}")
    private int num;
    @Override
    protected Object determineCurrentLookupKey() {
        String typeKey = DbContextHolder.getDbType();
        if(typeKey.equals(DbContextHolder.WRITE)) {
            return typeKey;
        }
        //使用随机数决定使用哪个读库
        //在1-N之间生成整型随机数
        int random = (int) (Math.random() * 1) + num;
        return DbContextHolder.READ + random;
    }
}

接着,我们需要创建一个 DataSourceConfig 类,用于配置数据源。具体实现如下:

@Configuration
public class DataSourceConfig {

    @Value("${mysql.datasource.type}")
    private Class<? extends DataSource> dataSourceType;

    /**
     * 写数据源
     * Primary 标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。
     * 多数据源配置的时候注意,必须要有一个主数据源,用 @Primary 标志该 Bean
     */
    @Primary
    @Bean
    @ConfigurationProperties(prefix = "mysql.datasource.write")
    public DataSource writeDataSource() {
        DataSource ds = DataSourceBuilder.create().type(dataSourceType).build();
        return ds;
    }

    @Bean
    @ConfigurationProperties(prefix = "mysql.datasource.read1")
    public DataSource readDataSource_1() {
        DataSource ds = DataSourceBuilder.create().type(dataSourceType).build();
        return ds;
    }

    /**
     * 设置数据源路由,通过该类中的determineCurrentLookupKey决定使用哪个数据源
     */
    @Bean
    public AbstractRoutingDataSource routingDataSource() {
        RoutingDataSource proxy = new RoutingDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DbContextHolder.WRITE, writeDataSource());
        targetDataSources.put(DbContextHolder.READ + "1", readDataSource_1());
        proxy.setDefaultTargetDataSource(writeDataSource());
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }

    /**
     * 由于Spring容器中现在有多个数据源,所以我们需要为事务管理器和MyBatis手动指定一个明确的数据源。
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(routingDataSource());
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        sqlSessionFactory.setConfiguration(configuration);
        return sqlSessionFactory.getObject();
    }

    @Bean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(routingDataSource());
    }
}

最后,我们需要使用AOP以注解方式切换只读数据库。具体实现如下:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReadOnly {
}
@Aspect
@Component
@Log4j2
public class DataSourceAop implements Ordered {

    @Around("@annotation(readOnly)")
    public Object setRead(ProceedingJoinPoint joinPoint, ReadOnly readOnly) throws Throwable{
        try {
            DbContextHolder.setDbType(DbContextHolder.READ);
            return joinPoint.proceed();
        } finally {
            //清除DbType一方面为了避免内存泄漏,更重要的是避免对后续在本线程上执行的操作产生影响
            DbContextHolder.clearDbType();
            log.info("清除threadLocal");
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

4、总结

通过本文的介绍,我们了解了如何使用 Spring Boot + MyBatis Plus + MySQL 实现读写分离。读写分离可以有效地分担数据库的读写负载,提高数据库的性能和可用性。希望本文能对读写分离的实现有所帮助。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
实现读写分离可以利用 SpringBootMybatisPlus 和 Druid 进行配置。下面是一个简单的实现过程: 1. 添加 MybatisPlus 和 Druid 的 Maven 依赖。 ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> ``` 2. 在配置文件中添加 Druid 数据源相关配置。 ```yaml spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource druid: initialSize: 5 maxActive: 10 minIdle: 5 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 20 filters: stat,wall,log4j connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 ``` 3. 配置 MybatisPlus 的多数据源功能。 ```java @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource masterDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.slave") public DataSource slaveDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slaveDataSource") DataSource slaveDataSource) { Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DataSourceType.MASTER.getType(), masterDataSource); targetDataSources.put(DataSourceType.SLAVE.getType(), slaveDataSource); return new DynamicDataSource(masterDataSource, targetDataSources); } } ``` 4. 创建一个 DataSourceHolder 类,用于保存当前线程的数据源类型。 ```java public class DataSourceHolder { private static final ThreadLocal<String> HOLDER = new ThreadLocal<>(); public static String getDataSource() { return HOLDER.get(); } public static void setDataSource(String dataSource) { HOLDER.set(dataSource); } public static void clearDataSource() { HOLDER.remove(); } } ``` 5. 创建一个枚举类型 DataSourceType,用于表示数据源类型。 ```java public enum DataSourceType { MASTER("master"), SLAVE("slave"); private final String type; DataSourceType(String type) { this.type = type; } public String getType() { return type; } } ``` 6. 创建一个 DynamicDataSource 类,继承 AbstractRoutingDataSource,用于动态切换数据源。 ```java public class DynamicDataSource extends AbstractRoutingDataSource { private final Map<Object, Object> targetDataSources; public DynamicDataSource(DataSource defaultDataSource, Map<Object, Object> targetDataSources) { super.setDefaultTargetDataSource(defaultDataSource); this.targetDataSources = targetDataSources; super.setTargetDataSources(targetDataSources); super.afterPropertiesSet(); } @Override protected Object determineCurrentLookupKey() { return DataSourceHolder.getDataSource(); } @Override public void setTargetDataSources(Map<Object, Object> targetDataSources) { this.targetDataSources.putAll(targetDataSources); super.setTargetDataSources(this.targetDataSources); super.afterPropertiesSet(); } @Override public void addTargetDataSource(Object key, Object dataSource) { this.targetDataSources.put(key, dataSource); super.setTargetDataSources(this.targetDataSources); super.afterPropertiesSet(); } } ``` 7. 创建一个 AopDataSourceConfig 类,用于配置切面,实现动态切换数据源。 ```java @Configuration public class AopDataSourceConfig { @Bean public DataSourceAspect dataSourceAspect() { return new DataSourceAspect(); } } ``` ```java @Aspect public class DataSourceAspect { @Pointcut("@annotation(com.example.demo.annotation.Master) " + "|| execution(* com.example.demo.service..*.select*(..)) " + "|| execution(* com.example.demo.service..*.get*(..)) " + "|| execution(* com.example.demo.service..*.query*(..)) " + "|| execution(* com.example.demo.service..*.find*(..)) " + "|| execution(* com.example.demo.service..*.count*(..))") public void read() { } @Pointcut("execution(* com.example.demo.service..*.insert*(..)) " + "|| execution(* com.example.demo.service..*.update*(..)) " + "|| execution(* com.example.demo.service..*.delete*(..))") public void write() { } @Around("read()") public Object read(ProceedingJoinPoint joinPoint) throws Throwable { try { DataSourceHolder.setDataSource(DataSourceType.SLAVE.getType()); return joinPoint.proceed(); } finally { DataSourceHolder.clearDataSource(); } } @Around("write()") public Object write(ProceedingJoinPoint joinPoint) throws Throwable { try { DataSourceHolder.setDataSource(DataSourceType.MASTER.getType()); return joinPoint.proceed(); } finally { DataSourceHolder.clearDataSource(); } } } ``` 8. 在 Service 层的方法上使用 @Master 注解,表示强制使用主库。 ```java @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override @Master public boolean save(User user) { return super.save(user); } } ``` 这样就实现读写分离功能。需要注意的是,在使用 MybatisPlus 进行 CRUD 操作时,需要使用对应的 Service 方法,例如 selectList、selectPage、insert、updateById、deleteById,而不是直接调用 Mapper 方法。否则,数据源切换将不会生效。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夕阳也是醉了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值