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進行查看登錄

到此這篇關於SpringBoot配置 Druid 三種方式(包括純配置文件配置)的文章就介紹到這瞭,更多相關SpringBoot配置 Druid內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: