springboot 通过gradle构建工具 配置druid监控

1.首先我们应该先导入druid的包

gradle导入druid依赖:

implementation 'org.springframework.boot:spring-boot-starter-log4j'

具体导入依赖如下:

springboot 通过gradle构建工具 配置druid监控_第1张图片

2.修改配置文件application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/admin?useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    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
    maxPoolPreparedStatementPerConnectionSize: 20
    filters: stat
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#更多操作可以防卫github上druid项目
    


3.通过将配置的servlet 和 filter bean对象加载到容器中

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }

    //配置Druid监控
    //1.管理后台的servlet
    @Bean
    public ServletRegistrationBean StatSViewServlet(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map map = new HashMap<>();
        map.put("loginUsername","admin");
        map.put("loginPassword","123456");
        map.put("allow","");
        servletRegistrationBean.setInitParameters(map);
        return servletRegistrationBean;
    }

    //2.配置监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map initparam = new HashMap<>();
        initparam.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initparam);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

通过@configurationProperties注解将存入容器的druiddaatasource的bean对象跟配置文件关联起来,自动会将配置文件中的配置加载到datasource中

你可能感兴趣的:(springboot)