Spring Boot + MyBatis-Plus 实现 MySQL 主从复制动态数据源切换


一、前言

下面是一个示例代码,展示如何在 Spring Boot 应用中实现 MySQL 主从复制的数据源动态切换。我们将使用 Spring Boot 和 MyBatis-Plus,并且结合 Spring 的动态数据源切换功能。
在这里插入图片描述

1. 添加依赖

首先,确保在 pom.xml 文件中添加了必要的依赖:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3</version>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.20</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

    </dependencies>

2. 配置主从数据源

application.ymlapplication.properties 中配置主从数据源:

server:
  port: 8082

spring:
  datasource:
    master:
      url: jdbc:mysql://master-db-host:3306/your_database?useSSL=false
      username: your_username
      password: your_password
      driver-class-name: com.mysql.cj.jdbc.Driver
    slave:
      url: jdbc:mysql://slave-db-host:3306/your_database?useSSL=false
      username: your_username
      password: your_password
      driver-class-name: com.mysql.cj.jdbc.Driver
      
mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml

3. 创建数据源配置类

DataSourceConfig 中配置数据源和动态路由:

@Configuration
@Data
public class DataSourceConfig {
    @Value("${spring.datasource.master.url}")
    private String dbUrl;
    @Value("${spring.datasource.master.username}")
    private String username;
    @Value("${spring.datasource.master.password}")
    private String password;
    @Value("${spring.datasource.master.driver-class-name}")
    private String driverClassName;


    @Value("${spring.datasource.slave.url}")
    private String slaveDbUrl;
    @Value("${spring.datasource.slave.username}")
    private String slaveUsername;
    @Value("${spring.datasource.slave.password}")
    private String slavePassword;
    @Value("${spring.datasource.slave.driver-class-name}")
    private String slaveDriverClassName;


    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create()
                .driverClassName(driverClassName)
                .url(dbUrl)
                .username(username)
                .password(password)
                .build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource() {

        return DataSourceBuilder.create()
                .driverClassName(slaveDriverClassName)
                .url(slaveDbUrl)
                .username(slaveUsername)
                .password(slavePassword)
                .build();

    }
}

4. 创建数据源上下文

DatabaseContextHolder 用于管理当前线程的数据源类型:

public class DatabaseContextHolder {

    private static final ThreadLocal<DatabaseType> contextHolder = new ThreadLocal<>();

    public static void setDatabaseType(DatabaseType databaseType) {
        contextHolder.set(databaseType);
    }

    public static DatabaseType getDatabaseType() {
        return contextHolder.get();
    }

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

5. 定义数据源类型

DatabaseType 枚举定义了数据源类型:

public enum DatabaseType {
    MASTER,
    SLAVE
}

6. 配置数据源切换

使用 AOP 来控制数据源切换,可以定义一个切面来切换数据源:

@Aspect
@Component
@EnableAspectJAutoProxy
public class DataSourceAspect {



    @Pointcut("@annotation(com.zbbmeta.annotation.DataSource)")
    public void dataSourcePointCut() {}

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (dataSource != null) {
            DatabaseContextHolder.setDatabaseType(dataSource.type());
        }

        try {
            return point.proceed();
        } finally {
            DatabaseContextHolder.clearDatabaseType();
        }
    }

}

7. 创建DynamicDataSourceConfig

@Configuration
@MapperScan("com.zbbmeta.mapper")
public class DynamicDataSourceConfig {
    @Autowired
    private DataSource masterDataSource;

    @Autowired
    private DataSource slaveDataSource;

    // 配置动态数据源
    @Bean
    @Primary
    public DataSource dynamicDataSource() {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DatabaseType.MASTER, masterDataSource);
        targetDataSources.put(DatabaseType.SLAVE, slaveDataSource);

        DynamicRoutingDataSource dynamicDataSource = new DynamicRoutingDataSource();
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource); // 设置默认数据源
        return dynamicDataSource;
    }

    // 配置 MyBatis 的 SqlSessionFactory
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dynamicDataSource) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dynamicDataSource);

        // 设置要扫描的 mapper 接口和 XML 文件路径
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        sessionFactoryBean.setTypeAliasesPackage("com.zbbmeta.entity");  // 设置实体类包路径

        return sessionFactoryBean.getObject();
    }

    // 配置 MyBatis 的 SqlSessionTemplate
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

8. 创建DynamicRoutingDataSource

public class DynamicRoutingDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DatabaseContextHolder.getDatabaseType();
    }
}

9. 创建注解

注解用于标记需要读操作的方法:

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {

    DatabaseType type() default DatabaseType.SLAVE;

}

10. 使用注解

@RestController
public class TutorialController {


    @Autowired
    private TutorialService tutorialService;


    @DataSource
    @GetMapping("/list")
    public List<Tutorial> list(){
        return tutorialService.list();

    }

    @DataSource(type = DatabaseType.MASTER)
    @GetMapping("/create")
    public Boolean create(){

        Tutorial tutorial = new Tutorial();
        tutorial.setTitle("master");
        tutorial.setDescription("master");

        return tutorialService.save(tutorial);
    }
}

这个示例展示了如何使用 Spring Boot 和 MyBatis-Plus 实现 MySQL 主从复制的数据源切换。你可以根据实际情况调整配置和代码。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
主从分离是一种常见的数据库优化策略,在高并发场景下可以提升系统的性能和可用性。下面是使用 Spring BootMybatis Plus 和 Druid 实现主从分离的步骤: 1. 引入依赖 在 pom.xml 文件中引入以下依赖: ```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. 配置数据源 在 application.yml 文件中配置主从数据源的信息: ```yaml spring: datasource: master: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/master_db?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true username: root password: root slave: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3307/slave_db?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true username: root password: root ``` 其中,master 和 slave 分别代表主库和从库的配置信息。 3. 配置 Druid 数据源 在 application.yml 文件中添加 Druid 数据源的配置: ```yaml spring: datasource: type: com.alibaba.druid.pool.DruidDataSource druid: initial-size: 5 min-idle: 5 max-active: 20 max-wait: 60000 time-between-eviction-runs-millis: 60000 min-evictable-idle-time-millis: 300000 validation-query: SELECT 1 FROM DUAL test-while-idle: true test-on-borrow: false test-on-return: false pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 filters: stat,wall,log4j connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 ``` 4. 配置 Mybatis Plus 在 application.yml 文件中添加 Mybatis Plus 的配置: ```yaml mybatis-plus: mapper-locations: classpath:mapper/**/*.xml global-config: db-config: id-type: auto field-strategy: not_null table-prefix: mp_ configuration: map-underscore-to-camel-case: true cache-enabled: false ``` 其中,mapper-locations 配置了 Mybatis Plus 的 Mapper 文件路径,global-config 配置了一些全局的配置,configuration 配置了 Mybatis 的一些参数。 5. 实现动态数据源 创建 DynamicDataSource 类,继承 AbstractRoutingDataSource,并实现 determineCurrentLookupKey() 方法: ```java public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.get(); } } ``` 其中,DataSourceContextHolder 是一个线程安全的类,用于存储当前线程使用的数据源类型。 6. 配置数据源路由 创建 DataSourceConfiguration 类,配置数据源路由: ```java @Configuration public class DataSourceConfiguration { @Bean public DataSource masterDataSource() { DruidDataSource dataSource = new DruidDataSource(); return dataSource; } @Bean public DataSource slaveDataSource() { DruidDataSource dataSource = new DruidDataSource(); return dataSource; } @Bean public DynamicDataSource dynamicDataSource() { DynamicDataSource dataSource = new DynamicDataSource(); Map<Object, Object> dataSourceMap = new HashMap<>(2); dataSourceMap.put("master", masterDataSource()); dataSourceMap.put("slave", slaveDataSource()); dataSource.setTargetDataSources(dataSourceMap); dataSource.setDefaultTargetDataSource(masterDataSource()); return dataSource; } @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dynamicDataSource()); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/**/*.xml")); } catch (IOException e) { throw new RuntimeException(e); } return sqlSessionFactoryBean.getObject(); } } ``` 其中,masterDataSource() 和 slaveDataSource() 分别返回主库和从库的 Druid 数据源,dynamicDataSource() 返回动态数据源,sqlSessionFactory() 配置了 Mybatis 的 SqlSessionFactory。 7. 实现数据源切换 创建 DataSourceContextHolder 类,用于在当前线程上存储数据源的类型: ```java public class DataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); public static void set(String dataSourceType) { contextHolder.set(dataSourceType); } public static String get() { return contextHolder.get(); } public static void clear() { contextHolder.remove(); } } ``` 创建 DataSourceAspect 类,实现切面拦截: ```java @Aspect @Component public class DataSourceAspect { @Before("@annotation(com.example.demo.annotation.Master) ") public void setMasterDataSource() { DataSourceContextHolder.set("master"); } @Before("@annotation(com.example.demo.annotation.Slave) ") public void setSlaveDataSource() { DataSourceContextHolder.set("slave"); } @After("@annotation(com.example.demo.annotation.Master) || @annotation(com.example.demo.annotation.Slave)") public void clearDataSource() { DataSourceContextHolder.clear(); } } ``` 其中,@Master 和 @Slave 是自定义的注解,用于标记使用主库和从库。 8. 实现主从分离 在 Mybatis Plus 的 Mapper 接口中,使用 @Master 和 @Slave 注解标记方法,实现主从分离: ```java public interface UserMapper extends BaseMapper<User> { @Master User selectById(Integer id); @Slave List<User> selectAll(); } ``` 其中,selectById() 方法使用主库,selectAll() 方法使用从库。 9. 测试主从分离 使用 JUnit 进行测试: ```java @SpringBootTest class DemoApplicationTests { @Autowired private UserMapper userMapper; @Test void contextLoads() { User user = userMapper.selectById(1); System.out.println(user.getName()); } @Test void testSelectAll() { List<User> userList = userMapper.selectAll(); userList.forEach(user -> System.out.println(user.getName())); } } ``` 其中,contextLoads() 方法测试使用主库,testSelectAll() 方法测试使用从库。 以上就是使用 Spring BootMybatis Plus 和 Druid 实现主从分离的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

和烨

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

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

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

打赏作者

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

抵扣说明:

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

余额充值