SpringBoot配置Druid与监控界面

1 引入依赖


<dependency>

    <groupId>com.alibaba</groupId>

    <artifactId>druid</artifactId>

    <version>1.1.10</version>

</dependency>

2 配置文件application.properties


#druid

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

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

spring.datasource.poolPreparedStatements=true

spring.datasource.filters=stat,wall,log4j

spring.datasource.maxPoolPreparedStatementPerConnectionSize=20

spring.datasource.useGlobalDataSourceStat=true

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

3 配置好之后,数据源是从默认的tomcat.pool切换到了druid,可是druid的属性比如initialSize、minIdle还未生效,因为在DataSourceProperties.class下没有对应的匹配项,还需要我们手动配置同时配置监控界面:

(1) 新建DruidConfig.java


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 java.util.Arrays;

import java.util.HashMap;

import java.util.Map;

@Configuration

public class DruidConfig{

    // 将所有前缀为spring.datasource下的配置项都加载到DataSource中

    @ConfigurationProperties(prefix ="spring.datasource")

@Bean

public DruidDataSource druidDataSource() {

return new DruidDataSource();

    }

@Bean

public ServletRegistrationBean druidStatViewServlet() {

ServletRegistrationBean servletRegistrationBean =new ServletRegistrationBean(new StatViewServlet(),"/druid/*");

        Map initParams =new HashMap<>();

        // 可配的属性都在 StatViewServlet 和其父类下

        initParams.put("loginUsername", "admin");

        initParams.put("loginPassword", "admin");

        servletRegistrationBean.setInitParameters(initParams);

        return servletRegistrationBean;

    }

@Bean

public FilterRegistrationBean druidWebStatFilter() {

FilterRegistrationBean filterRegistrationBean =new FilterRegistrationBean(new WebStatFilter());

        Map initParams =new HashMap<>();

        initParams.put("exclusions", "*.js,*.css,/druid/*");

        filterRegistrationBean.setInitParameters(initParams);

        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));

        return filterRegistrationBean;

    }

}

(2)打开浏览器访问:http://localhost:8080/druid/login.html

到这里就配置好了

推荐阅读更多精彩内容