MySQL学习笔记:Druid连接池基础教程——从入门到监控实战
Druid 是什么
Druid 是阿里巴巴开源的数据库连接池组件,号称"为监控而生"。它不仅是一个连接池,还内置了 监控统计、SQL 防火墙、慢 SQL 日志 等功能。
与主流连接池对比
| 特性 | Druid | HikariCP | DBCP2 | C3P0 |
|---|---|---|---|---|
| 性能 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ |
| 监控面板 | ✅ 内置 Web 控制台 | ❌ 需要集成 | ❌ | ❌ |
| SQL 防火墙 | ✅ WallFilter | ❌ | ❌ | ❌ |
| 慢 SQL 日志 | ✅ 内置 | ❌ | ❌ | ❌ |
| 连接泄漏检测 | ✅ remove-abandoned | ❌ | ✅ | ✅ |
| PSCache 缓存 | ✅ 可配置 | ✅ 默认开启 | ✅ | ✅ |
| Spring Boot 集成 | ✅ 官方 Starter | ✅ Spring Boot 默认 | ❌ | ❌ |
| 活跃用户 | 国内主流 | 全球主流 | 较少 | 较少 |
结论:HikariCP 性能略优(Spring Boot 默认),但 Druid 胜在功能全面——一个依赖解决连接池 + 监控 + 防火墙三个问题,特别适合国内项目。
入门:基础连接配置
1. 环境
- Spring Boot 4.1.0
- Java 21
- PostgreSQL 16(Docker 部署)
- Maven
2. 添加依赖
<!-- PostgreSQL 驱动 -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Druid Spring Boot 4 Starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-4-starter</artifactId>
<version>1.2.28</version>
</dependency>
⚠️ 关键注意:Druid 的 Starter 按 Spring Boot 大版本区分,不能混用:
- Spring Boot 2.x →
druid-spring-boot-starter- Spring Boot 3.x →
druid-spring-boot-3-starter- Spring Boot 4.x →
druid-spring-boot-4-starter如果 Starter 与 Spring Boot 版本不匹配,启动时会报
ClassNotFoundException: DataSourceProperties。
3. application.yaml 配置
spring:
datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://localhost:15432/blog
username: postgres
password: 123456
druid:
# ---------- 连接池大小 ----------
initial-size: 5 # 启动时创建 5 个连接
min-idle: 5 # 最少保持 5 个空闲
max-active: 20 # 最多 20 个活跃连接
# ---------- 连接获取超时 ----------
max-wait: 60000 # 获取连接超时 60s
# ---------- 连接保活检测 ----------
time-between-eviction-runs-millis: 60000 # 检测线程运行间隔
min-evictable-idle-time-millis: 300000 # 空闲 5min 才被驱逐
validation-query: SELECT 1 # 心跳 SQL
test-while-idle: true # 空闲时检测(推荐)
test-on-borrow: false # 获取时检测(关掉,更快)
test-on-return: false # 归还时检测(关掉,更快)
4. 参数详解
| 参数 | 作用 | 调优建议 |
|---|---|---|
initial-size |
启动时预创建连接数 | 低并发 5,高并发 10-20 |
min-idle |
最少空闲连接 | 与 initial-size 一致 |
max-active |
最大活跃连接 | 根据 (核数 × 2) + 磁盘数 估算,建议压测确定 |
max-wait |
获取连接超时 | 一般 30s,结合熔断使用 |
validation-query |
心跳 SQL | MySQL 用 SELECT 1,Oracle 用 SELECT 1 FROM DUAL |
test-while-idle |
空闲时后台检测 | 推荐开启,不阻塞业务 |
test-on-borrow |
每次获取都检测 | 关闭,性能损耗大(除非对连接可靠性要求极高) |
5. 编写测试代码
@SpringBootTest
class DruidTestApplicationTests {
@Autowired
private DataSource dataSource;
@Test
void testDruidDataSource() throws SQLException {
System.out.println("数据源类型: " + dataSource.getClass().getName());
try (Connection connection = dataSource.getConnection()) {
System.out.println("获取连接成功!连接对象: " + connection);
}
}
}
运行结果:
数据源类型: com.alibaba.druid.spring.boot4.autoconfigure.DruidDataSourceWrapper
获取连接成功!连接对象: com.alibaba.druid.pool.DruidStatementConnection@49bb808f
DruidDataSourceWrapper是 Druid Spring Boot Starter 封装的连接池,它继承自DruidDataSource。
进阶使用:监控控制台
1. 添加监控配置
spring:
datasource:
druid:
# ... 连接池配置同上 ...
# ---------- 监控统计 ----------
filter:
stat:
enabled: true # 启用 StatFilter(关键!)
log-slow-sql: true # 记录慢 SQL
slow-sql-millis: 1000 # 超过 1s 算慢
merge-sql: true # 合并同类 SQL(? 参数归一)
# ---------- Web 访问统计 ----------
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
session-stat-enable: true
session-stat-max-count: 1000
# ---------- 监控控制台 ----------
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
login-username: admin
login-password: 123456
2. 踩坑:Spring Bean 方式 vs filters: stat
⚠️ 常见坑点
Druid 有两种方式启用过滤器,效果完全不同。错误方式(filters 属性):
filters: stat,wall # Druid FilterManager 创建 → @ConfigurationProperties 不生效,log-slow-sql 设了也没用正确方式(Spring Bean):
filter: stat: enabled: true # DruidFilterConfiguration 创建 Spring Bean → 属性绑定生效 log-slow-sql: true slow-sql-millis: 1000原因:
druid-spring-boot-starter中DruidFilterConfiguration.statFilter()方法有@ConditionalOnProperty(prefix = "spring.datasource.druid.filter.stat", name = "enabled"),且没有matchIfMissing,必须显式设置enabled: true才会创建 StatFilter Bean,log-slow-sql等属性才被绑定到该 Bean 上。
3. 访问监控控制台
启动项目后打开:http://localhost:8080/druid/index.html
输入账号密码(admin / 123456)进入。
⚠️ Docker 部署
如果你的项目在 Docker 容器中运行,通过端口映射访问控制台时,会报Sorry, you are not permitted to view this page.这是因为
druid-spring-boot-4-starter默认allow只允许127.0.0.1,而 Docker 端口映射后来源 IP 变成 Docker 网桥网关(172.17.0.x),不是127.0.0.1。解决方案:
stat-view-servlet: enabled: true allow: "" # 设为空字符串,表示允许所有 IP # 或者指定允许的网段 # allow: 127.0.0.1,172.0.0.0/8
4. 查看 SQL 监控
对着应用发几个请求(注意请求必须通过 Druid 数据源,直接操作数据库不会被记录):

控制台可以看到:
- 数据源 — 当前活跃/空闲连接数、逻辑/物理连接计数
- SQL 监控 — 每个 SQL 的执行次数、总耗时、慢 SQL 记录
- URI 监控 — 每个接口的调用次数与耗时
- Session 监控 — 当前 Session 列表
总结
| 阶段 | 核心要点 |
|---|---|
| 入门 | 选择对应 Spring Boot 版本的 Starter,配置 application.yaml |
| 连接池 | initial-size / min-idle / max-active 控制大小,test-while-idle 保活 |
| 监控 | StatFilter 启用监控,WebStatFilter 统计 URI,StatViewServlet 展示控制台 |
| 坑 | filter.stat.enabled: true(而不是 filters: stat),Docker 部署需要 allow: "" |

浙公网安备 33010602011771号