SpringBoot 三种方式配置 Druid(包括纯配置文件配置)

记录一下在项目中用纯 YML(application.yml 或者 application.properties)文件、Java 代码配置 Bean 和注解三种方式配置 Alibaba Druid 用于监控或者查看 SQL 状况:

1. 纯配置文件 .yml 或者 .properties

(1)pom.xml 添加相关依赖

        <!-- SPRINGBOOT WEB -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- SPRINGBOOT DRUID -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        
        <!-- SPRINGBOOT JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
<!-- MYSQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>${mysql-connector-java.version}</scope> </dependency> <!-- LOG4J --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> <scope>compile</scope> </dependency>

(2)配置 application.yml 或者 application.properties 文件,本次配置文件为 application.yml

spring:
  # 数据源配置
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
   # MYSQL 5 驱动:com.mysql.jdbc.Driver,MYSQL 6+ 驱动:com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=GMT%2B8 username: root password: 123456 # 连接池配置 druid: # 初始化大小,最小,最大 initial-size: 5 min-idle: 5 max-active: 20 # 配置获取连接等待超时的时间 max-wait: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒 time-between-eviction-runs-millis: 60000 # 配置一个连接在池中最小生存时间 min-evictable-idle-time-millis: 300000 validation-query: SELECT 1 FROM sys_user test-while-idle: true test-on-borrow: false test-on-return: false # 打开 PSCache,并且指定每个连接上 PSCache 的大小 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 # 配置监控统计拦截的 Filter,去掉后监控界面 SQL 无法统计,wall 用于防火墙 filters: stat,wall,log4j # 通过 connection-properties 属性打开 mergeSql 功能;慢 SQL 记录 connection-properties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000 # 配置 DruidStatFilter web-stat-filter: enabled: true url-pattern: /* exclusions: .js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/* # 配置 DruidStatViewServlet stat-view-servlet: url-pattern: /druid/* # IP 白名单,没有配置或者为空,则允许所有访问 allow: 127.0.0.1 # IP 黑名单,若白名单也存在,则优先使用 deny: 192.168.31.253 # 禁用 HTML 中 Reset All 按钮 reset-enable: false # 登录用户名/密码 login-username: root login-password: 123

(3)启动 SpringBoot 项目访问地址 http://localhost:8080/druid/login.html 进行登录,若出现一下界面则配置成功

 

2. Java 代码配置 Bean

(1)pom.xml 依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>

(2)在配置文件 application.yml 中添加 Druid 配置

spring:
    datasource:
        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

(3)添加 DruidConfig.java 配置文件

import javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.sql.DataSource;

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 com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
public class DruidConfig {

    @Bean
    // 将所有前缀为spring.datasource下的配置项都加载DataSource中
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    @Bean
    public ServletRegistrationBean<Servlet> druidServlet() {
        // 进行 druid 监控的配置处理
        ServletRegistrationBean<Servlet> srb = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/**");
        // 白名单
        srb.addInitParameter("allow", "127.0.0.1");
        // 黑名单
        srb.addInitParameter("deny", "192.168.31.253");
        // 用户名
        srb.addInitParameter("loginUsername", "root");
        // 密码
        srb.addInitParameter("loginPassword", "root");
        // 是否可以重置数据源
        srb.addInitParameter("resetEnable", "false");
        return srb;
    }
    
    @Bean
    public FilterRegistrationBean<Filter> filterRegistrationBean() {
        FilterRegistrationBean<Filter> frb = new FilterRegistrationBean<>();
        frb.setFilter(new WebStatFilter());
        // 所有请求进行监控处理
        frb.addUrlPatterns("/*");
        // 排除名单
        frb.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");
        return frb;
    }

}

(4)启动 SpringBoot 项目访问地址 http://localhost:8080/druid/login.html 进行查看登录

 

3. 注解

(1)pom.xml 文件中添加 Druid 依赖(同方式二)

(2)配置文件添加信息(同方式二)

(3)配置 WebServlet

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

import com.alibaba.druid.support.http.StatViewServlet;
@WebServlet(urlPatterns = "/druid/*", 
    initParams={
            @WebInitParam(name="allow",value="192.168.16.110,127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问)
            @WebInitParam(name="deny",value="192.168.16.111"),// IP黑名单 (存在共同时,deny优先于allow)
            @WebInitParam(name="loginUsername",value="admin"),// 用户名
            @WebInitParam(name="loginPassword",value="admin"),// 密码
            @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能
    })
public class DruidServlet extends StatViewServlet {

    private static final long serialVersionUID = 1L;

}

(4)配置 WebFilter

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

import com.alibaba.druid.support.http.WebStatFilter;

@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
initParams={
    @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源
})
public class DruidFilter extends WebStatFilter {

}

(5)配置启动文件 SpringBootApplication 用于扫描我们配置的类

  添加 @ServletComponentScan 注解进行扫描

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan("com.uy.servlet")
public class SpringBootApplication{

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication.class, args); } }

(6)启动 SpringBoot 项目访问地址 http://localhost:8080/druid/login.html 进行查看登录

 

posted @ 2019-04-27 17:03  走在一线的码农  阅读(48068)  评论(1编辑  收藏  举报