SpringBoot統計、監控SQL運行情況的方法詳解

1 基本概念

Druid 是Java語言中最好的數據庫連接池。

雖然 HikariCP 的速度稍快,但是,Druid能夠提供強大的監控和擴展功能,也是阿裡巴巴的開源項目。

Druid是阿裡巴巴開發的號稱為監控而生的數據庫連接池,在功能、性能、擴展性方面,都超過其他數據庫連接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource等等等,秒殺一切。

Druid 可以很好的監控 DB 池連接和 SQL 的執行情況,天生就是針對監控而生的 DB 連接池。

Spring Boot 默認數據源 HikariDataSource 與 JdbcTemplate中已經介紹 Spring Boot 2.x 默認使用 Hikari 數據源,可以說 Hikari 與 Driud 都是當前 Java Web 上最優秀的數據源。

而Druid已經在阿裡巴巴部署瞭超過600個應用,經過好幾年生產環境大規模部署的嚴苛考驗!

  • stat:Druid內置提供一個StatFilter,用於統計監控信息。
  • wall:Druid防禦SQL註入攻擊的WallFilter就是通過Druid的SQL Parser分析。Druid提供的SQL Parser可以在JDBC層攔截SQL做相應處理,比如說分庫分表、審計等。
  • log4j2:這個就是 日志記錄的功能,可以把sql語句打印到log4j2 供排查問題。

2 添加依賴

pom.xml

<!-- 阿裡巴巴的druid數據源 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.23</version>
</dependency>
<!-- mysql8 驅動-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!--使用 log4j2 記錄日志-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!--
mybatis,引入瞭 SpringBoot的 JDBC 模塊,
所以,默認是使用 hikari 作為數據源
-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
    <exclusions>
        <!-- 排除默認的 HikariCP 數據源 -->
        <exclusion>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </exclusion>
    </exclusions>
</dependency>

3 配置相關屬性

配置Druid數據源(連接池): 如同以前 c3p0、dbcp 數據源可以設置數據源連接初始化大小、最大連接數、等待時間、最小連接數 等一樣,Druid 數據源同理可以進行設置;

配置 Druid web 監控 filter(WebStatFilter): 這個過濾器的作用就是統計 web 應用請求中所有的數據庫信息,比如 發出的 sql 語句,sql 執行的時間、請求次數、請求的 url 地址、以及seesion 監控、數據庫表的訪問次數 等等。

配置 Druid 後臺管理 Servlet(StatViewServlet): Druid 數據源具有監控的功能,並提供瞭一個 web 界面方便用戶查看,類似安裝 路由器 時,人傢也提供瞭一個默認的 web 頁面;需要設置 Druid 的後臺管理頁面的屬性,比如 登錄賬號、密碼 等;

註意:

Druid Spring Boot Starter 配置屬性的名稱完全遵照 Druid,可以通過 Spring Boot 配置文件來配置Druid數據庫連接池和監控,如果沒有配置則使用默認值。

application.yml

########## 配置數據源 (Druid)##########
spring:
  datasource:
    ########## JDBC 基本配置 ##########
    username: xxx
    password: xxx
    driver-class-name: com.mysql.cj.jdbc.Driver   # mysql8 的連接驅動
    url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai
    platform: mysql                               # 數據庫類型
    type: com.alibaba.druid.pool.DruidDataSource  # 指定數據源類型
    ########## 連接池 配置 ##########
    druid:
      # 配置初始化大小、最小、最大
      initial-size: 5
      minIdle: 10
      max-active: 20
      # 配置獲取連接等待超時的時間(單位:毫秒)
      max-wait: 60000
      # 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
      time-between-eviction-runs-millis: 2000
      # 配置一個連接在池中最小生存的時間,單位是毫秒
      min-evictable-idle-time-millis: 600000
      max-evictable-idle-time-millis: 900000
      # 用來測試連接是否可用的SQL語句,默認值每種數據庫都不相同,這是mysql
      validationQuery: select 1
      # 應用向連接池申請連接,並且testOnBorrow為false時,連接池將會判斷連接是否處於空閑狀態,如果是,則驗證這條連接是否可用
      testWhileIdle: true
      # 如果為true,默認是false,應用向連接池申請連接時,連接池會判斷這條連接是否是可用的
      testOnBorrow: false
      # 如果為true(默認false),當應用使用完連接,連接池回收連接的時候會判斷該連接是否還可用
      testOnReturn: false
      # 是否緩存preparedStatement,也就是PSCache。PSCache對支持遊標的數據庫性能提升巨大,比如說oracle
      poolPreparedStatements: true
      # 要啟用PSCache,必須配置大於0,當大於0時, poolPreparedStatements自動觸發修改為true,
      # 在Druid中,不會存在Oracle下PSCache占用內存過多的問題,
      # 可以把這個數值配置大一些,比如說100
      maxOpenPreparedStatements: 20
      # 連接池中的minIdle數量以內的連接,空閑時間超過minEvictableIdleTimeMillis,則會執行keepAlive操作
      keepAlive: true
      # Spring 監控,利用aop 對指定接口的執行時間,jdbc數進行記錄
      aop-patterns: "com.springboot.template.dao.*"
      ########### 啟用內置過濾器(第一個 stat必須,否則監控不到SQL)##########
      filters: stat,wall,log4j2
      # 自己配置監控統計攔截的filter
      filter:
        # 開啟druiddatasource的狀態監控
        stat:
          enabled: true
          db-type: mysql
          # 開啟慢sql監控,超過2s 就認為是慢sql,記錄到日志中
          log-slow-sql: true
          slow-sql-millis: 2000
        # 日志監控,使用slf4j 進行日志輸出
        slf4j:
          enabled: true
          statement-log-error-enabled: true
          statement-create-after-log-enabled: false
          statement-close-after-log-enabled: false
          result-set-open-after-log-enabled: false
          result-set-close-after-log-enabled: false
      ########## 配置WebStatFilter,用於采集web關聯監控的數據 ##########
      web-stat-filter:
        enabled: true                   # 啟動 StatFilter
        url-pattern: /*                 # 過濾所有url
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" # 排除一些不必要的url
        session-stat-enable: true       # 開啟session統計功能
        session-stat-max-count: 1000    # session的最大個數,默認100
      ########## 配置StatViewServlet(監控頁面),用於展示Druid的統計信息 ##########
      stat-view-servlet:
        enabled: true                   # 啟用StatViewServlet
        url-pattern: /druid/*           # 訪問內置監控頁面的路徑,內置監控頁面的首頁是/druid/index.html
        reset-enable: false              # 不允許清空統計數據,重新計算
        login-username: root            # 配置監控頁面訪問密碼
        login-password: 123
        allow: 127.0.0.1           # 允許訪問的地址,如果allow沒有配置或者為空,則允許所有訪問
        deny:                                        # 拒絕訪問的地址,deny優先於allow,如果在deny列表中,就算在allow列表中,也會被拒絕

上述配置文件的參數可以在 com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties 和 org.springframework.boot.autoconfigure.jdbc.DataSourceProperties中找到;

3.1 如何配置 Filter

可以通過 spring.datasource.druid.filters=stat,wall,log4j …的方式來啟用相應的內置Filter,不過這些Filter都是默認配置。如果默認配置不能滿足需求,可以放棄這種方式,通過配置文件來配置Filter,下面是例子。

# 配置StatFilter  
spring.datasource.druid.filter.stat.enabled=true
spring.datasource.druid.filter.stat.db-type=h2
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000
# 配置WallFilter  
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.db-type=h2
spring.datasource.druid.filter.wall.config.delete-allow=false
spring.datasource.druid.filter.wall.config.drop-table-allow=false

目前為以下 Filter 提供瞭配置支持,根據(spring.datasource.druid.filter.*)進行配置。

  • StatFilter
  • WallFilter
  • ConfigFilter
  • EncodingConvertFilter
  • Slf4jLogFilter
  • Log4jFilter
  • Log4j2Filter
  • CommonsLogFilter

不想使用內置的 Filters,要想使自定義 Filter 配置生效需要將對應 Filter 的 enabled 設置為 true ,Druid Spring Boot Starter 默認禁用 StatFilter,可以將其 enabled 設置為 true 來啟用它。

4 監控頁面

(1)啟動項目後,訪問/druid/login.html來到登錄頁面,輸入用戶名密碼登錄

(2)數據源頁面 是當前DataSource配置的基本信息,上述配置的Filter可以在裡面找到,如果沒有配置Filter(一些信息會無法統計,例如“SQL監控”,會無法獲取JDBC相關的SQL執行信息)

(3) SQL監控頁面,統計瞭所有SQL語句的執行情況

(4)URL監控頁面,統計瞭所有Controller接口的訪問以及執行情況

(5)Spring 監控頁面,利用aop 對指定接口的執行時間,jdbc數進行記錄

(6)SQL防火墻頁面

druid提供瞭黑白名單的訪問,可以清楚的看到sql防護情況。

(7)Session監控頁面

可以看到當前的session狀況,創建時間、最後活躍時間、請求次數、請求時間等詳細參數。

(8)JSONAPI 頁面

通過api的形式訪問Druid的監控接口,api接口返回Json形式數據。

5 sql監控

配置 Druid web 監控 filter(WebStatFilter)這個過濾器,作用就是統計 web 應用請求中所有的數據庫信息,比如 發出的 sql 語句,sql 執行的時間、請求次數、請求的 url 地址、以及seesion 監控、數據庫表的訪問次數 等等。

spring:
  datasource:
    druid:
      ########## 配置WebStatFilter,用於采集web關聯監控的數據 ##########
      web-stat-filter:
        enabled: true                   # 啟動 StatFilter
        url-pattern: /*                 # 過濾所有url
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" # 排除一些不必要的url
        session-stat-enable: true       # 開啟session統計功能
        session-stat-max-count: 1000    # session的最大個數,默認100

6 慢sql記錄

有時候,系統中有些SQL執行很慢,我們希望使用日志記錄下來,可以開啟Druid的慢SQL記錄功能

spring:
  datasource:
    druid:
      filter:
        stat:
          enabled: true         # 開啟DruidDataSource狀態監控
          db-type: mysql        # 數據庫的類型
          log-slow-sql: true    # 開啟慢SQL記錄功能
          slow-sql-millis: 2000 # 默認3000毫秒,這裡超過2s,就是慢,記錄到日志

啟動後,如果遇到執行慢的SQL,便會輸出到日志中

7 spring 監控

訪問之後spring監控默認是沒有數據的;

這需要導入SprngBoot的AOP的Starter

<!--SpringBoot 的aop 模塊-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

需要在 application.yml 配置:

Spring監控AOP切入點,如com.springboot.template.dao.*,配置多個英文逗號分隔

spring.datasource.druid.aop-patterns="com.springboot.template.dao.*"

8 去 Ad(廣告)

訪問監控頁面的時候,你可能會在頁面底部(footer)看到阿裡巴巴的廣告

原因:引入的druid的jar包中的common.js(裡面有一段js代碼是給頁面的footer追加廣告的)

如果想去掉,有兩種方式:

(1) 直接手動註釋這段代碼

如果是使用Maven,直接到本地倉庫中,查找這個jar包

要註釋的代碼:

// this.buildFooter();

common.js的位置:

com/alibaba/druid/1.1.23/druid-1.1.23.jar!/support/http/resources/js/common.js

(2) 使用過濾器過濾

註冊一個過濾器,過濾common.js的請求,使用正則表達式替換相關的廣告內容

@Configuration
@ConditionalOnWebApplication
@AutoConfigureAfter(DruidDataSourceAutoConfigure.class)
@ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled",
havingValue = "true", matchIfMissing = true)
public class RemoveDruidAdConfig {
    /**
    * 方法名: removeDruidAdFilterRegistrationBean
    * 方法描述 除去頁面底部的廣告
    * @param properties com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties
    * @return org.springframework.boot.web.servlet.FilterRegistrationBean
    */
    @Bean
    public FilterRegistrationBean removeDruidAdFilterRegistrationBean(DruidStatProperties properties) {
        // 獲取web監控頁面的參數
        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        // 提取common.js的配置路徑
        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
        final String filePath = "support/http/resources/js/common.js";
        //創建filter進行過濾
        Filter filter = new Filter() {
            @Override
            public void init(FilterConfig filterConfig) throws ServletException {}
            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                chain.doFilter(request, response);
                // 重置緩沖區,響應頭不會被重置
                response.resetBuffer();
                // 獲取common.js
                String text = Utils.readFromResource(filePath);
                // 正則替換banner, 除去底部的廣告信息
                text = text.replaceAll("<a.*?banner\"></a><br/>", "");
                text = text.replaceAll("powered.*?shrek.wang</a>", "");
                response.getWriter().write(text);
            }
            @Override
            public void destroy() {}
        };
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(commonJsPattern);
        return registrationBean;
    }
}

兩種方式都可以,建議使用的是第一種,從根源解決

9 獲取 Druid 的監控數據

Druid 的監控數據可以在 開啟 StatFilter 後,通過 DruidStatManagerFacade 進行獲取;

DruidStatManagerFacade#getDataSourceStatDataList 該方法可以獲取所有數據源的監控數據,

除此之外 DruidStatManagerFacade 還提供瞭一些其他方法,可以按需選擇使用。

@RestController
@RequestMapping(value = "/druid")
public class DruidStatController {
    @GetMapping("/stat")
    public Object druidStat(){
        // 獲取數據源的監控數據
        return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
    }
}

總結 

到此這篇關於SpringBoot統計、監控SQL運行情況的文章就介紹到這瞭,更多相關SpringBoot統計監控SQL運行內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: