实际开发中实现多数据源配置,需要在默认配置中浅做修改
1.导入依赖
<!-- 动态数据源 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<!-- alibaba Driud数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.20</version>
</dependency>
2.修改application.yml文件
修改前
db:
conn:
str: useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/magic_test?${db.conn.str}
username: root
password: 2333
修改后
db:
conn:
str: useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
spring:
datasource:
m1:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/magic_test1?${db.conn.str}
username: root
password: 2333
m2:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/magic_test2?${db.conn.str}
username: root
password: 2333
3.创建多数据配置文件 DataSourceConfig.java
@Configuration
public class DataSourceConfig {
@Primary //标记主数据源,当存在多个DataSource Bean时,默认使用该数据源
@Bean(name = "m1") //创建一个名为"m1"的DataSource Bean
@Qualifier("m1")
@ConfigurationProperties(prefix = "spring.datasource.m1") //将属性文件配置注入到DataSource实例中
public DataSource magicDataSource(){
return DataSourceBuilder.create().build();
}
@Bean(name = "m2")
@Qualifier("m2")
@ConfigurationProperties(prefix = "spring.datasource.m2")
public DataSource pmDataSource(){
return DataSourceBuilder.create().build();
}
// 创建一个MagicDynamicDataSource类型的Bean,用于管理多个数据源并实现动态切换
@Bean
public MagicDynamicDataSource magicDynamicDataSource(){
MagicDynamicDataSource dynamicDataSource = new MagicDynamicDataSource();
// 将默认数据源设置为m1,并将m2的DataSource加入到动态数据源管理器中
dynamicDataSource.setDefault(magicDataSource());
dynamicDataSource.add("m2",pmDataSource());
return dynamicDataSource;
}
}
4.magic-api接口测试
测试结果