掘金 后端 ( ) • 2024-04-20 15:56

在构建复杂的企业级应用时,我们经常面临需要同时访问多个数据库的情况。利用 Spring Boot 和 MyBatis-Plus 的强大功能,我们可以有效地管理和配置多数据源。本文将详细介绍如何在 Spring Boot 应用中结合 MyBatis-Plus 实现多数据源的配置和使用。

引入必要的依赖

首先,为了支持动态数据源,我们需要在项目的 pom.xml 文件中添加 MyBatis-Plus 的动态数据源启动器依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>请替换为最新版本</version>
</dependency>

配置数据源

application.yml 文件中,我们将定义两个数据源:org 作为默认数据源,和 gzl_dept 作为第二数据源。这里是如何配置它们的示例:

spring:
  datasource:
    dynamic:
      primary: org 
      datasource:
        org:
          url: jdbc:mysql://192.168.0.111:3306/org?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true
          username: root
          password: root
          driver-class-name: com.mysql.cj.jdbc.Driver
        gzl_dept:
          url: jdbc:mysql://192.168.0.111:3306/gzl_dept?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true
          username: root
          password: root
          driver-class-name: com.mysql.cj.jdbc.Driver

使用 @DS 注解进行数据源切换

在业务逻辑中,我们可以通过 @DS 注解来指定使用哪个数据源。这个注解可以应用于 Service 层或 Mapper 层的方法上,如下所示:

@Service
public class BusinessService {
    @Autowired
    private BusinessMapper businessMapper;

    
    public BusinessData getDefaultBusinessData(Long id) {
        return businessMapper.selectById(id);
    }

    
    @DS("gzl_dept")
    public BusinessData getSpecialBusinessData(Long id) {
        return businessMapper.selectById(id);
    }
}

注意事项

  • 数据源一致性:确保 @DS 注解中的数据源名称与 application.yml 中配置的名称完全匹配。
  • 注解优先级:如果同时在类和方法上使用了 @DS,则方法上的注解具有更高的优先级。
  • 事务处理:在跨数据源操作中,需要注意事务的处理。由于 MyBatis-Plus 的动态数据源不支持跨数据源事务,可能需要采用分布式事务管理策略。

结语

通过上述步骤,你可以在 Spring Boot 应用中灵活地配置和切换多个数据源。这种能力极大地增强了应用处理多种存储需求的灵活性,使得开发者可以更加专注于业务逻辑的实现,而不是数据源的管理。