Configuring Druid DataSource Monitoring and Filters in Spring Boot
This guide explains the fundamentals of Druid as a Java database connection pool, how to add required Maven dependencies, configure various Druid properties and filters for SQL and web monitoring, enable slow‑SQL logging, integrate Spring AOP monitoring, remove the default Alibaba advertisement, and retrieve monitoring data via the DruidStatManagerFacade API.
Druid is a Java database connection pool developed by Alibaba, offering powerful monitoring and extensibility features that surpass other pools such as HikariCP, C3P0, and DBCP. It provides built‑in filters like StatFilter for statistics, WallFilter for SQL injection protection, and log4j2 for logging.
1. Adding Dependencies
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.23</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
<exclusions>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</exclusion>
</exclusions>
</dependency>2. Configuring Druid Properties
The application.yml file can be used to set datasource credentials, driver class, URL, and Druid‑specific pool settings such as initial-size , minIdle , max-active , and validation queries. Filters are enabled via the filters property (e.g., stat,wall,log4j2 ), and the WebStatFilter is configured to monitor web requests.
spring:
datasource:
druid:
# JDBC basic configuration
username: xxx
password: xxx
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai
platform: mysql
type: com.alibaba.druid.pool.DruidDataSource
# Connection pool configuration
initial-size: 5
minIdle: 10
max-active: 20
max-wait: 60000
min-evictable-idle-time-millis: 600000
max-evictable-idle-time-millis: 900000
validationQuery: select 1
testWhileIdle: true
testOnBorrow: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
keepAlive: true
aop-patterns: "com.springboot.template.dao.*"
# Enable built‑in filters
filters: stat,wall,log4j2
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: false
login-username: root
login-password: 123
allow: 127.0.0.1
deny: ""3. Enabling SQL Monitoring and Slow‑SQL Logging
By setting log-slow-sql: true and slow-sql-millis: 2000 in the stat filter configuration, Druid records any SQL that exceeds two seconds, outputting it to the log.
spring:
datasource:
druid:
filter:
stat:
enabled: true
db-type: mysql
log-slow-sql: true
slow-sql-millis: 20004. Spring AOP Monitoring
Adding the spring-boot-starter-aop dependency and configuring spring.datasource.druid.aop-patterns enables method‑level monitoring of DAO calls.
spring.datasource.druid.aop-patterns="com.springboot.template.dao.*"5. Removing the Default Alibaba Advertisement
The Druid UI includes a footer advertisement injected by common.js . It can be removed either by editing the JAR‑packed common.js (commenting out // this.buildFooter(); ) or by registering a custom servlet filter that rewrites the JavaScript response.
@Configuration
@ConditionalOnWebApplication
public class RemoveDruidAdConfig {
@Bean
public FilterRegistrationBean removeDruidAdFilterRegistrationBean(DruidStatProperties properties) {
DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
Filter filter = new Filter() {
@Override public void init(FilterConfig filterConfig) throws ServletException {}
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
response.resetBuffer();
String text = Utils.readFromResource("support/http/resources/js/common.js");
text = text.replaceAll("\n", "");
text = text.replaceAll("powered.*?shrek.wang", "");
response.getWriter().write(text);
}
@Override public void destroy() {}
};
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(filter);
registrationBean.addUrlPatterns(commonJsPattern);
return registrationBean;
}
}6. Accessing Druid Monitoring Data Programmatically
After enabling StatFilter , the DruidStatManagerFacade API can retrieve datasource statistics, e.g., via DruidStatManagerFacade#getDataSourceStatDataList() . A simple REST controller can expose this data as JSON.
@RestController
@RequestMapping("/druid")
public class DruidStatController {
@GetMapping("/stat")
public Object druidStat() {
// Get datasource monitoring data
return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
}
}The document concludes with a promotional section unrelated to the technical content.
IT Architects Alliance
Discussion and exchange on system, internet, large‑scale distributed, high‑availability, and high‑performance architectures, as well as big data, machine learning, AI, and architecture adjustments with internet technologies. Includes real‑world large‑scale architecture case studies. Open to architects who have ideas and enjoy sharing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.