美文网首页
spring-boot配置多数据源

spring-boot配置多数据源

作者: MaJiT | 来源:发表于2021-03-01 12:47 被阅读0次

1.引入dynamic-datasource-spring-boot-starter。

        <!-- 多数据源 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>

2.配置数据源

server:
  port: 8080
spring:
  datasource:
    dynamic:
      primary: master #设置默认的数据源或者数据源组,默认值即为master
      strict: false #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源.
      datasource:
        master:
          type: com.alibaba.druid.pool.DruidDataSource
          url: jdbc:mysql://localhost:3306/test1
          username: root
          password: 1234
          driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
        test1:
          type: com.alibaba.druid.pool.DruidDataSource
          url: jdbc:mysql://localhost:3306/test2
          username: root
          password: 1234
          driver-class-name: com.mysql.jdbc.Driver
        test2:
          driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
          type: com.alibaba.druid.pool.DruidDataSource
          url: jdbc:sqlserver://192.168.10.10:1433;DatabaseName=test3
          username: sa
          password: 1234
#mybatis plus 配置-------------------------------------------------------------------------------------
mybatis-plus:
  mapper-locations: classpath*:/mapper/**/**Mapper.xml
  #数据库主键生成策略
  global-config:
    db-config:
      id-type: uuid
    # 关闭MP3.0自带的banner
    banner: false
  configuration:
    # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    # 返回类型为Map,显示null对应的字段
    call-setters-on-nulls: true

3.使用 @DS 切换数据源。

@DS 可以注解在方法上或类上,同时存在就近原则 方法上注解 优先于 类上注解。

@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    @Resource
    private PaymentMapper paymentMapper;

    @Override
    public Payment test1() {
        return paymentMapper.selectById("8e5b23687fd2196632de17fe33a3516c");
    }

    @Override
    @DS("test2")
    public Payment test2() {
        return paymentMapper.selectById("123123");
    }
}

相关文章

网友评论

      本文标题:spring-boot配置多数据源

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