一、环境

       <!--   spring web 基础   -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    <!--   mysql 连接包   -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    <!--   mybatis plus   -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--    mybatis Plus 多数据源    -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

二、配置

spring:
  datasource:
    dynamic:
      // 设置默认的数据源或者数据源组,默认值即为master
      primary: master
      // 严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源 
      strict: false 
      datasource:
      // 主数据库
        master:
          url: jdbc:mysql://localhost:3306/study_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
          username: root
          password: root
      // 副数据库
        slave:
          url: jdbc:mysql://localhost:3306/study_demo2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
          username: root
          password: root

三、使用

1、Mapper

@Mapper
@DS("master")
public interface Student1Mapper extends BaseMapper<Student> {
}
@Mapper
@DS("slave")
public interface Student2Mapper extends BaseMapper<Student> {
}

2、Demo

    @Autowired
    private StudentMapper studentMapper;

    @Test
    void moreDatasource(){
        // 数据库 master
        System.out.println(student1Mapper.selectList(new QueryWrapper<>()).get(0));
        // 数据库 slave
        System.out.println(student2Mapper.selectList(new QueryWrapper<>()).get(0));
    }

3、结果

// 该对象存在数据源 master中
Student(id=1, name=demo1, sex=null, grade=null)
// 该对象存在数据源 slave中
Student(id=33, name=demo2, sex=null, grade=null)

版权声明:本文为qq_42151956原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_42151956/article/details/124749883