springboot 搭建druid数据监控
1 配置application.yml
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
# schema:
# - classpath:employee.sql
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
2 spring-boot 默认是使用tomcat的数据源 所以配置了必须写配置类
learn/src/main/java/springboot/learn/config/DruidConfig.java
package springboot.learn.config; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.springframework.boot.context.properties.ConfigurationProperties; 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; import javax.sql.DataSource; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @Configuration public class DruidConfig { //切换datasource配置 默认使用tomcat 不切换druid配置不生效 @ConfigurationProperties(prefix = "spring.datasource")//配置切换路径 @Bean public DataSource dataSource(){ return new DruidDataSource(); } //使用druid进行web的数据监控 //配置servlet后台监控 @Bean public ServletRegistrationBean servletRegistrationBean(){ ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");//配置druid servlet后台配置路径 System.out.println("ServletRegistrationBean......"); System.out.println(bean); Map<String,String> initParams = new HashMap<>(); initParams.put("loginUsername","admin");//监控后台用户名 initParams.put("loginPassword","123456");//监控后台密码 initParams.put("allow","");//默认允许所有访问 initParams.put("deny","192.168.15.21"); bean.setInitParameters(initParams); return bean; } //配置filter过滤 @Bean public FilterRegistrationBean filterRegistrationBean(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>(); initParams.put("exclusions","*.js,*.css,/druid/*"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; } }
访问域名 http://localhost:8080/druid