美文网首页
mybatis-plus配置多数据源(dynamic-datas

mybatis-plus配置多数据源(dynamic-datas

作者: 无我_无他_有你 | 来源:发表于2022-07-29 16:33 被阅读0次

前提:已整合mybatis-plus
官方文档地址:https://baomidou.com/pages/a61e1b/

引入依赖 (其支持 Jdk 1.7+, SpringBoot 1.4.x 1.5.x 2.x.x。)

<dynamic-datasource-version>3.3.1</dynamic-datasource-version>
<!-- 多数据库动态配置 -->
<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
  <version>${dynamic-datasource-version}</version>
</dependency>

yml配置

spring:
  datasource:
    dynamic:
      primary: master #设置默认的数据源或者数据源组,默认值即为master
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        #配置默认的数据源连接
        master:
          url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
        slave_1:
          url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
        slave_2:
          url: ENC(xxxxx) # 内置加密,使用请查看详细文档
          username: ENC(xxxxx)
          password: ENC(xxxxx)
          driver-class-name: com.mysql.jdbc.Driver
       #......省略
       #以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2

用法
使用 @DS 切换数据源。
@DS 可以注解在方法上或类上,同时存在就近原则 方法上注解 优先于 类上注解。
没有贴@DS注解,默认表示访问默认数据库

@Service
@DS("slave")
public class UserServiceImpl implements UserService {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public List selectAll() {
    return  jdbcTemplate.queryForList("select * from user");
  }
  
  @Override
  @DS("slave_1")
  public List selectByCondition() {
    return  jdbcTemplate.queryForList("select * from user where age >10");
  }
}

相关文章

网友评论

      本文标题:mybatis-plus配置多数据源(dynamic-datas

      本文链接:https://www.haomeiwen.com/subject/dcjqwrtx.html