pom.xml
<properties>
<dynamic-datasource.version>3.2.1</dynamic-datasource.version>
<mybatis-plus.version>3.4.2</mybatis-plus.version>
<druid.version>1.2.4</druid.version>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>${dynamic-datasource.version}</version>
</dependency>
</dependencies>
application.yml
spring:
#多数据源配置
datasource:
druid:
stat-view-servlet:
enabled: true
loginUsername: 954L
loginPassword: 123456
destroy-scheduler: close
filter:
stat:
log-slow-sql: true # 开启慢查询记录
slow-sql-millis: 5000 # 慢 SQL 的标准,单位:毫秒
merge-sql: true # SQL合并配置
dynamic:
primary: read # 默认的数据源;命名规则:组名_xxx;指定组名根据特定算法返回任意一个数据源
datasource:
read_1:
url: ${site.mysql.data-url}
username: ${site.mysql.username}
password: ${site.mysql.password}
read_2:
url: ${site.mysql.data-url}
username: ${site.mysql.username}
password: ${site.mysql.password}
write:
url: ${site.mysql.data-url}
username: ${site.mysql.username}
password: ${site.mysql.password}
Application.java
# 移除Druid自动装配数据源
@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class})
public class SiteApplication extends SpringBootServletInitializer
如何切换数据源
@DS("write")
@Transactional(rollbackFor = Exception.class)
public Object saveByDto(PolicyAddDto policyAddDto, SystemUser systemUser)
@DS(“数据源名”):在Service层添加注解即可切换数据源,不加注解默认采用上文填写的read
踩坑记录
springboot druid连接池多数据源SQL错误sql injection violation, multi-statement not