mybatis-plus(五)-mybatis处理多数据源

mybatisplus多数据源

引入依赖

<dependency>
    <groupId>com.baomidougroupId>
    <artifactId>dynamic-datasource-spring-boot-starterartifactId>
    <version>2.5.6version>
dependency>

配置文件

创建一个数据用户,控制其权限

mysql> create user 'slave01'@'%' identified WITH mysql_native_password by '123';
Query OK, 0 rows affected (0.00 sec)

mysql> grant select ON *.* to 'slave01'@'%';
Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

配置application.yml

spring:
  datasource:
    dynamic:
      druid:
        initial-size: 1
        max-active: 20
        min-idle: 2
        max-wait: 6000
      primary: mysql_master
      datasource:
        mysql_master:
          url: jdbc:mysql://192.168.198.128:3306/book_db?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
          username: root
          password: 123
          driver-class-name: com.mysql.cj.jdbc.Driver
        slave_01:
          url: jdbc:mysql://192.168.198.128:3310/book_db?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
          username: rdb
          password: 123
          driver-class-name: com.mysql.cj.jdbc.Driver

在使用处添加@DS

在类或方法上添加@DS,切换数据源

@DS("mysql_slave")
@Override
public List<BookVo> findAll() {
    List<Book> list = bookDao.selectList(null);
    List<BookVo> bookVoList = new ArrayList<>(50);
    list.forEach(e->bookVoList.add(new BookVo(e,null)));
    return bookVoList;
}

测试写入数据到只读数据源

image-20230702224147558

你可能感兴趣的:(mybatis-plus,mybatis,android)