SpringBoot多數據源yaml配置
1.配置多數據源
- pom文件
-
<dependency> <groupId>com.baomidou</groupId> <artifactId>dynamic-datasource-spring-boot-starter</artifactId> <version>2.5.6</version> </dependency>
-
- yaml文件(一定對齊)
- 第一種
spring: datasource: dynamic: primary: db1 datasource: db1: username: root password: root url: jdbc:mysql://127.0.0.1:3306/db1 driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource db2: username: root2 password: root2 url: jdbc:mysql://127.0.0.1:3306/db2 driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource - 第二種
spring: datasource: dynamic: datasource: master_db1: username: root password: root url: jdbc:mysql://127.0.0.1:3306/db1 driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource db2: username: root2 password: root2 url: jdbc:mysql://127.0.0.1:3306/db2 driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource druid: initial-size: 20 minIdle: 50 #最小連接池數量 xxxxxxxxx
- 第一種
2.設置默認數據源
??配置中的 primary: db1 , 即是指定默認使用的數據庫
spring:
datasource:
dynamic:
primary: db1
3.使用注解切換數據源
- 類上
@DS("db2") public class xxx(){} - 方法上
@DS("db2") public void xxx(){} - mapper方法上
@Select("SELECT SFZH,USER_NAME,SEX FROM T_USER_INFO WHERE A = #{A}") @DS("db2") Map<String, Object> queryView(@Param("A") String A);
4.其他配置 , 啟動
修改Application注解
@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)

浙公網安備 33010602011771號