前提:在SpringBoot整合JDBC的基础上完成Druid的整合
SpringBoot整合JDBC 可参考--------> SpringBoot整合JDBC_Maiko Star的博客-CSDN博客
1. 添加Druid依赖
在pom.xml
文件中添加Druid的依赖项。例如:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
2. 配置Druid连接池
在application.properties
或application.yml
配置文件中,添加以下Druid连接池的配置:
使用application.properties
:
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# Druid配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-active=20
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-while-idle=true
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=30000
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
spring.datasource.druid.filters=stat,wall,log4j
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
使用application.yml
:
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydatabase
username: root
password: your_password
driver-class-name: com.mysql.cj.jdbc.Driver
## Druid配置
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 5
min-idle: 5
max-active: 20
test-on-borrow: false
test-while-idle: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 30000
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
filters: stat,wall,log4j
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
3. 创建数据源配置
创建一个Java配置类,用于配置Druid数据源,并注入到Spring Boot中。例如:
@Configuration
public class DataSourceConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource dataSource() {
return DruidDataSourceBuilder.create
4.测试
可以通过测试类打断点的方式,debug查看配置参数是否生效