Druid 作為阿里巴巴開源的高性能資料庫連線池,內建強大的 SQL 監控、統計分析與防火牆功能。本文詳細示範如何在 Spring Boot 專案中整合 Druid,並啟用多維度監控儀表板。
<dependencies>
<!-- Spring Boot 基礎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Druid 連線池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.18</version>
</dependency>
<!-- MySQL 驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
server:
port: 8080
servlet:
context-path: /druid-demo
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/myblog?useSSL=false&serverTimezone=UTC
username: root
password: root
# 連線池核心參數
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# PSCache 優化
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 監控攔截器:stat-統計、wall-防火牆、log4j-日誌
filters: stat,wall,slf4j
# 連線屬性:合併 SQL、慢查詢閾值 5 秒
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
@Configuration
public class DruidMonitorConfig {
@Bean
public ServletRegistrationBean<StatViewServlet> statViewServlet() {
ServletRegistrationBean<StatViewServlet> bean =
new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
bean.addInitParameter("allow", "127.0.0.1,192.168.10.25"); // 白名單
bean.addInitParameter("deny", "192.168.1.73"); // 黑名單
bean.addInitParameter("loginUsername", "admin");
bean.addInitParameter("loginPassword", "securePassword123");
bean.addInitParameter("resetEnable", "false"); // 禁用重置功能
return bean;
}
@Bean
public FilterRegistrationBean<WebStatFilter> webStatFilter() {
FilterRegistrationBean<WebStatFilter> bean =
new FilterRegistrationBean<>(new WebStatFilter());
bean.addUrlPatterns("/*");
bean.addInitParameter("exclusions", "*.js,*.css,*.png,*.jpg,*.gif,*.ico,/druid/*");
bean.addInitParameter("profileEnable", "true"); // 開啟 URL 調用統計
return bean;
}
}
spring:
datasource:
druid:
stat-view-servlet:
enabled: true
url-pattern: /druid/*
allow: 127.0.0.1
login-username: admin
login-password: securePassword123
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: "*.js,*.css,*.png,*.jpg,*.gif,*.ico,/druid/*"
profile-enable: true
啟動專案後訪問 https://localhost:8080/druid-demo/druid/index.html,主要監控維度:
slf4j 替代 log4j,統一日誌框架druid.stat.slowSqlMillis 與日誌告警系統druid.stat.mergeSql=true 合併參數化 SQL 統計Druid 不僅是高性能連線池,更是生產環境 SQL 可觀測性的利器。透過 Spring Boot 自動配置與少量客製化,即可獲得企業級的資料庫監控能力,助力效能調優與故障快速定位。