概念
一般来说,我们正常的业务只涉及一个数据源,在特定的业务场景中需要使用多个数据源的情况,就需要配置多个数据源来满足特定的业务需求。本文介绍的是:springboot 整合 dynamic-datasource 来实现多数据源的配置使用。注意:此处可以整合多种不同类型的数据库。
配置
1、引入 pom 依赖(主要依赖)
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
2、yml 配置文件
server:
port: 8081
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
dynamic:
primary: master
strict: false
datasource:
master:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db2021?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&nuLlCatalogMeansCurrent=true
username: root
password: 123456
flowable:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/flowable?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&nuLlCatalogMeansCurrent=true
username: root
password: 123456
3、多数据源配置类
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Bean(name = "flowableDataSource")
@ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.flowable")
public DataSource flowableDataSource() {
return DataSourceBuilder.create()
.type(DruidDataSource.class)
.build();
}
@Bean(name = "masterDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.master")
public DataSource masterDataSource() {
return DataSourceBuilder.create()
.type(DruidDataSource.class)
.build();
}
}
多数据源使用
注:@DS可以放在类上 或 方法上
@DS("master")
public void doOperationWithMaster(){
}
@DS("flowable")
public void doOperationWithOther(){
}
@DSTransactional
public void doOperation(){
}
|