【SpringBoot+mybatis-puls实现多数据源配置】

SpringBoot+mybatis-puls实现多数据源配置+问题参考:


SpringBoot+mybatis-puls实现多数据源配置,引入druid-spring-boot-starter直接省去了手写配置类,具体实现步骤如下:


实现步骤:

  1. 在pom.xml文件中引入dynamic-datasource-spring-boot-starter与druid-spring-boot-starter两个依赖。(前者是基于Spring Boot的快速集成多数据源的启动器,后者可以帮你在Spring Boot项目中轻松集成Druid数据库连接池和监控。)代码如下:
        <dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
			<version>3.5.1</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.2.6</version>
		</dependency>

2.在application.yml文件中编写数据源的配置,代码及注释如下:

spring:
  autoconfigure:
    #自动化配置 例外处理
    exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
  datasource:
    #数据库连接池,不用自己写配置
    type: com.alibaba.druid.pool.DruidDataSource
    dynamic:
      #默认库
      primary: dbone
      datasource:
        dbone:
          url: jdbc:postgresql://xx.xxx.xx.x:xxxx/db_name?currentSchema=name
          username: postgresql
          password: postgresql
          driver-class-name: org.postgresql.Driver
        dbtwo:
          url: jdbc:postgresql://xx.xxx.xx.x:xxxx/db_name?currentSchema=name
          username: postgresql
          password: postgresql
          driver-class-name: org.postgresql.Driver

3.在不同的类使用不同的数据源时加上注解@DS("数据源名称")

操作顺利的话在执行上述步骤后,多数据源的配置就完成了。
若有报错,可以在下面看看有没有和我遇到了相同的错误:


遇到的问题:

(1)问题一
Invocation of init method failed; nested exception is java.lang.RuntimeException: 请检查primary默认数据库设置

仔细检查数据库连接配置是写正确了

(2)问题二

An attempt was made to call a method that does not exist. The attempt was made from the following lo在这里插入图片描述
图片出现的问题是我在配置.yml时没加上面代码块里自动化配置的那两行

(3)问题三

Correct the classpath of your application so that it contains a single, compatible version of com.alibaba.druid.util.StringUtils
在这里插入图片描述
最后图上这个报错是因为在pom文件中添加的两个依赖包版本与spring包的版本不兼容。建议搜索与自己项目匹配的版本导入。

上述就是我在配置多数据源时所遇到的问题,简单做此记录。

版权声明:本文为qq_43707906原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。