SpringBoot配置双数据源(Mysql和Postgre)

449 阅读2分钟

本文已参与[新人创作礼]活动,一起开启掘金创作之路

SpringBoot配置双数据源(Mysql和Postgre)


git地址: https://gitee.com/chenoubaya/two_datasource.git

我们话不多说,直接上操作步骤

一、首先引入依赖

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
		
		<!-- 重要-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>

二、修改配置文件

==注意==:配置文件根据自己的数据库配置,主要是IP,用户名和密码,这里省略了

spring:
  datasource:
    dynamic:
      #默认使用的是gp数据库,对应下面gp和mysql,可视情况更改
      primary: gp	
      strict: false
      datasource:
        gp:
          url: jdbc:postgresql://10.0.xxx.112:5432/gp_sydb
          username: gpadmin
          password: gpadmin
          driver-class-name: org.postgresql.Driver
          type: com.alibaba.druid.pool.DruidDataSource
        mysql:
          url: jdbc:mysql://localhost:3306/test
          username: root
          password: xxxx
          driver-class-name: com.mysql.jdbc.Driver
          type: com.alibaba.druid.pool.DruidDataSource

      druid:
        #初始连接数
        initial-size: 1
        #最小连接数
        min-idle: 1
        #最大连接数
        max-active: 100
        #获取连接池超时时间
        max-wait: 60000
        filters: config,stat
        connect-properties: druid.stat.mergeSql=true;druid.stat.logSlowSql=true;druid.stat.slowSqlMillis=500
        filter:
          commons-log:
            enabled: true
            statement-log-enabled: false
            statement-log-error-enabled: true
            statement-executable-sql-log-enable: true

三、配置启动类(根据自己配置来写)

==注意==:主要是@MapperScan注解中的值填写正确

@SpringBootApplication
@MapperScan(value = {"com.gdsz.mapper.*"})
public class GennlifeGdszApplication {

    public static void main(String[] args) {
        SpringApplication.run(GennlifeGdszApplication.class, args);
    }
}

四、配置mybatis的mapper映射文件

#mybaites
mybatis.mapper-locations= classpath:mapper/*/*.xml
mybatis.type-aliases-package=com.smqd.entity

==注意==:本人这样写是因为自己的mapper文件路径自己配置,实际要按照自己的来配置 本人实际路径如下,

五、配置mybatis的mapper映射文件

@Mapper
@DS(value = "gp")
public interface Db2UserMapper {
    List<User> getUserbyId(Long id);
}
@Mapper
@DS("mysql")
public interface Db1UserMapper {
    User getUser(Integer id);
}

到此为止,配置双数据源完成,可以成功从不同库查询数据

六、总结

1,首先依赖是必不可少的, 2,配置文件按照自己的需求认真填写, 3,启动类上的@MapperScan注解不能丢,要把里面value的值填写正确, 4,在Mapper接口上,打上@DS("mysql")注解,告知该Mapper接口使用的是那个数据库, 5,配置的时候会遇到问题,个人认为,主要集中在配置上,比如配置文件里面的路径,mapper扫描的路径,大家细心细心.