1.使用环境
springboot 3.4.3
java 17
2.引入依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.clojars.zentrope</groupId>
<artifactId>ojdbc</artifactId>
<version>11.2.0.3.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.8</version>
</dependency>
3.yml配置
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master:
driver-class-name: com.mysql.cj.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
url: jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf8
username: mytest
password: mytest
slave_1:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://127.0.0.1:5432/postgres
username: postgres
password: postgres
4.使用
@GetMapping("/{id}")
@DS("master")
public Result get(@PathVariable("id") Long id) {
AiFeatureVO aiFeatureVO = aiFeatureService.get(id);
return Result.success(aiFeatureVO);
}
@GetMapping("/testSalver")
@DS("slave_1")
public Result testSalver() {
return Result.success(aiFeatureService.testServer());
}
5.踩过的坑
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
原因:
springboot用的是3.x.x但是动态数据源用的不是相匹配的版本,之前用的是这个版本,所以就报错了,这个是springboot2.x.x匹配的版本
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency>
处理方法:
把动态数据源换成springboot3匹配的版本就行了
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
<version>4.3.0</version>
</dependency>
之前找了好久没发现问题,后来看到另一篇文章
https://blog.youkuaiyun.com/u013737132/article/details/134888348
才找到错误,此处做个笔记,希望可以帮到遇到同样问题的人。