Springboot集成Druid实现监控功能
在Spring Boot项目中,要使用Druid实现数据库监控,你需要做以下几步操作:
- 添加Druid依赖到你的
pom.xml
文件中:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
- 在
application.properties
或application.yml
中配置Druid属性:
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/yourdb
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# Druid数据源配置
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=1
spring.datasource.druid.max-active=10
spring.datasource.druid.max-wait=60000
# 配置Druid监控页面
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.security.filter-enabled=false
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.enabled=true
- 在Spring Boot应用中添加Druid监控Servlet配置:
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DruidConfig {
@Bean
public ServletRegistrationBean<StatViewServlet> druidServlet() {
ServletRegistrationBean<StatViewServlet> servletRegistrationBean =
new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// 可以添加初始化参数来配置白名单、黑名单、登录用户名和密码等
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean<WebStatFilter> druidFilter() {
FilterRegistrationBean<WebStatFilter> filterRegistrationBean =
new FilterRegistrationBean<>(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*
评论已关闭