一、开启 Druid 监控的核心配置
基本配置(application.yml)
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 监控配置(核心部分)
stat-view-servlet:
enabled: true # 开启监控页面
url-pattern: /druid/* # 访问路径
login-username: admin # 登录用户名
login-password: admin # 登录密码
allow: 192.168.0.0/16 # 允许访问的IP段
deny: '' # 拒绝访问的IP
reset-enable: false # 禁用重置按钮
二、解决 Spring Security 拦截问题
安全配置类
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// 放行Druid监控路径
.antMatchers("/druid/**").permitAll()
// 其他安全规则
.antMatchers("/api/**").authenticated()
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
// 关闭Druid路径的CSRF保护
.csrf().ignoringAntMatchers("/druid/**")
// 添加HTTP头安全策略(可选)
.and()
.headers()
.contentSecurityPolicy("script-src 'self'; object-src 'none'");
}
// 完全忽略静态资源的安全过滤
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers(
"/druid/**",
"/css/**", "/js/**", "/images/**",
"/webjars/**", "/favicon.ico"
);
}
}
三、访问 Druid 监控页面
1.访问地址
http://<服务器IP>:<端口>/druid
示例:
http://192.168.11.201:8080/druid
2.登录凭证
- 用户名:admin(配置文件中指定的login-username)
- 密码:admin(配置文件中指定的login-password)
四、常见问题解决方案
1.访问被拒绝(403错误)
原因:
- Spring Security 未放行路径
- Druid IP 白名单限制
解决:
- 检查 SecurityConfig 中是否有 .antMatchers(“/druid/**”).permitAll()
- 检查 Druid 配置中的 allow 设置
- 临时测试:设置 allow: ‘’
2.现象:页面样式错乱,功能异常
原因:
- 静态资源加载失败
解决:
// 在 SecurityConfig 中添加
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/druid/**");
}
3.监控数据不显示
原因:
- SQL监控过滤器未启用
解决:
druid:
filters: stat,wall
filter:
stat:
enabled: true