springboot项目中访问druid内置监控页面

2023年1月16日08:58:17

1、首先加入druid依赖

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid-spring-boot-starter</artifactId>

<version>1.1.9</version>

  </dependency>

2、设置配置文件:

# 数据库访问配置

# 主数据源,默认的

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/test

spring.datasource.username=root

spring.datasource.password=123456

 

# 下面为连接池的补充设置,应用到上面所有数据源中

# 初始化大小,最小,最大

spring.datasource.initialSize=5

spring.datasource.minIdle=5

spring.datasource.maxActive=20

# 配置获取连接等待超时的时间

spring.datasource.maxWait=60000

# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒

spring.datasource.timeBetweenEvictionRunsMillis=60000

# 配置一个连接在池中最小生存的时间,单位是毫秒

spring.datasource.minEvictableIdleTimeMillis=300000

spring.datasource.validationQuery=SELECT 1 FROM DUAL

spring.datasource.testWhileIdle=true

spring.datasource.testOnBorrow=false

spring.datasource.testOnReturn=false

# 打开PSCache,并且指定每个连接上PSCache的大小

spring.datasource.poolPreparedStatements=true

spring.datasource.maxPoolPreparedStatementPerConnectionSize=20

# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙

spring.datasource.filters=stat,wall,log4j

# 通过connectProperties属性来打开mergeSql功能;慢SQL记录

spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

# 合并多个DruidDataSource的监控数据

#spring.datasource.useGlobalDataSourceStat=true

注意点:

配置oracle数据库时 spring.datasource.validationQuery=SELECT 1 FROM DUAL否则会报语法错误

如果springboot中使用的默认的logback日志框架,不要设置filters=log4j,否则会报错:

Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Priority

stat查看sql的,wall是防火墙
3、设置druid访问页面的用户名和密码,只需要在springboot启动类中加入@bean配置即可:

@Bean

public ServletRegistrationBean<StatViewServlet> druidStatViewServlet() {

ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

registrationBean.addInitParameter("allow", "127.0.0.1");// IP白名单 (没有配置或者为空,则允许所有访问)

registrationBean.addInitParameter("deny", "");// IP黑名单 (存在共同时,deny优先于allow)

registrationBean.addInitParameter("loginUsername", "root");

registrationBean.addInitParameter("loginPassword", "1234");

registrationBean.addInitParameter("resetEnable", "false");

return registrationBean;

}

4、启动项目后,访问页面http://127.0.0.1:8001/druid/index.html,就可以访问监控页面了,其中ip和端口号为项目的ip和端口号。页面效果如下:

  • 作者:qq_34412985
  • 原文链接:https://blog.csdn.net/qq_34412985/article/details/107731103
    更新时间:2023年1月16日08:58:17 ,共 2215 字。