1. 程式人生 > >Druid Spring Boot Starter實現監控

Druid Spring Boot Starter實現監控

  1. 在 Spring Boot 專案中加入druid-spring-boot-starter依賴

    Maven
    
    <dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid-spring-boot-starter</artifactId>
       <version>1.1.10</version>
    </dependency>
    Gradle
    
    compile 'com.alibaba:druid-spring-boot-starter:1.1.10'

     

  2. 新增配置

    spring.datasource.url= 
    spring.datasource.username=
    spring.datasource.password=
    # ...其他配置(可選,不是必須的,使用內嵌資料庫的話上述三項也可省略不填)

     

配置屬性

Druid Spring Boot Starter 配置屬性的名稱完全遵照 Druid,你可以通過 Spring Boot 配置檔案來配置Druid資料庫連線池和監控,如果沒有配置則使用預設值。

  • JDBC 配置
spring.datasource.druid.url= # 或spring.datasource.url= 
spring.datasource.druid.username= # 或spring.datasource.username=
spring.datasource.druid.password= # 或spring.datasource.password=
spring.datasource.druid.driver-class-name= #或 spring.datasource.driver-class-name=
  • 連線池配置
spring.datasource.druid.initial-size=
spring.datasource.druid.max-active=
spring.datasource.druid.min-idle=
spring.datasource.druid.max-wait=
spring.datasource.druid.pool-prepared-statements=
spring.datasource.druid.max-pool-prepared-statement-per-connection-size= 
spring.datasource.druid.max-open-prepared-statements= #和上面的等價
spring.datasource.druid.validation-query=
spring.datasource.druid.validation-query-timeout=
spring.datasource.druid.test-on-borrow=
spring.datasource.druid.test-on-return=
spring.datasource.druid.test-while-idle=
spring.datasource.druid.time-between-eviction-runs-millis=
spring.datasource.druid.min-evictable-idle-time-millis=
spring.datasource.druid.max-evictable-idle-time-millis=
spring.datasource.druid.filters= #配置多個英文逗號分隔
....//more
  • 監控配置
# WebStatFilter配置,說明請參考Druid Wiki,配置_配置WebStatFilter
spring.datasource.druid.web-stat-filter.enabled= #是否啟用StatFilter預設值true
spring.datasource.druid.web-stat-filter.url-pattern=
spring.datasource.druid.web-stat-filter.exclusions=
spring.datasource.druid.web-stat-filter.session-stat-enable=
spring.datasource.druid.web-stat-filter.session-stat-max-count=
spring.datasource.druid.web-stat-filter.principal-session-name=
spring.datasource.druid.web-stat-filter.principal-cookie-name=
spring.datasource.druid.web-stat-filter.profile-enable=

# StatViewServlet配置,說明請參考Druid Wiki,配置_StatViewServlet配置
spring.datasource.druid.stat-view-servlet.enabled= #是否啟用StatViewServlet預設值true
spring.datasource.druid.stat-view-servlet.url-pattern=
spring.datasource.druid.stat-view-servlet.reset-enable=
spring.datasource.druid.stat-view-servlet.login-username=
spring.datasource.druid.stat-view-servlet.login-password=
spring.datasource.druid.stat-view-servlet.allow=
spring.datasource.druid.stat-view-servlet.deny=

# Spring監控配置,說明請參考Druid Github Wiki,配置_Druid和Spring關聯監控配置
spring.datasource.druid.aop-patterns= # Spring監控AOP切入點,如x.y.z.service.*,配置多個英文逗號分隔

Druid Spring Boot Starter 不僅限於對以上配置屬性提供支援,DruidDataSource 內提供setter方法的可配置屬性都將被支援。你可以參考WIKI文件或通過IDE輸入提示來進行配置。配置檔案的格式你可以選擇.properties.yml,效果是一樣的,在配置較多的情況下推薦使用.yml

如何配置多資料來源

  1. 新增配置
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=

# Druid 資料來源配置,繼承spring.datasource.* 配置,相同則覆蓋
...
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=5
...

# Druid 資料來源 1 配置,繼承spring.datasource.druid.* 配置,相同則覆蓋
...
spring.datasource.druid.one.max-active=10
spring.datasource.druid.one.max-wait=10000
...

# Druid 資料來源 2 配置,繼承spring.datasource.druid.* 配置,相同則覆蓋
...
spring.datasource.druid.two.max-active=20
spring.datasource.druid.two.max-wait=20000
...

強烈注意:Spring Boot 2.X 版本不再支援配置繼承,多資料來源的話每個資料來源的所有配置都需要單獨配置,否則配置不會生效

  1. 建立資料來源
@Primary
@Bean
@ConfigurationProperties("spring.datasource.druid.one")
public DataSource dataSourceOne(){
    return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.two")
public DataSource dataSourceTwo(){
    return DruidDataSourceBuilder.create().build();
}

如何配置 Filter

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

# 配置StatFilter 
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 配置不再演示

目前為以下 Filter 提供了配置支援,請參考文件或者根據IDE提示(spring.datasource.druid.filter.*)進行配置。

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

要想使自定義 Filter 配置生效需要將對應 Filter 的 enabled 設定為 true ,Druid Spring Boot Starter 預設會啟用 StatFilter,你也可以將其 enabled 設定為 false 來禁用它。

如何獲取 Druid 的監控資料

Druid 的監控資料可以通過 DruidStatManagerFacade 進行獲取,獲取到監控資料之後你可以將其暴露給你的監控系統進行使用。Druid 預設的監控系統資料也來源於此。下面給做一個簡單的演示,在 Spring Boot 中如何通過 HTTP 介面將 Druid 監控資料以 JSON 的形式暴露出去,實際使用中你可以根據你的需要自由地對監控資料、暴露方式進行擴充套件。

@RestController
public class DruidStatController {
    @GetMapping("/druid/stat")
    public Object druidStat(){
        // DruidStatManagerFacade#getDataSourceStatDataList 該方法可以獲取所有資料來源的監控資料,除此之外 DruidStatManagerFacade 還提供了一些其他方法,你可以按需選擇使用。
        return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
    }
}
[
  {
    "Identity": 1583082378,
    "Name": "DataSource-1583082378",
    "DbType": "h2",
    "DriverClassName": "org.h2.Driver",
    "URL": "jdbc:h2:file:./demo-db",
    "UserName": "sa",
    "FilterClassNames": [
      "com.alibaba.druid.filter.stat.StatFilter"
    ],
    "WaitThreadCount": 0,
    "NotEmptyWaitCount": 0,
    "NotEmptyWaitMillis": 0,
    "PoolingCount": 2,
    "PoolingPeak": 2,
    "PoolingPeakTime": 1533782955104,
    "ActiveCount": 0,
    "ActivePeak": 1,
    "ActivePeakTime": 1533782955178,
    "InitialSize": 2,
    "MinIdle": 2,
    "MaxActive": 30,
    "QueryTimeout": 0,
    "TransactionQueryTimeout": 0,
    "LoginTimeout": 0,
    "ValidConnectionCheckerClassName": null,
    "ExceptionSorterClassName": null,
    "TestOnBorrow": true,
    "TestOnReturn": true,
    "TestWhileIdle": true,
    "DefaultAutoCommit": true,
    "DefaultReadOnly": null,
    "DefaultTransactionIsolation": null,
    "LogicConnectCount": 103,
    "LogicCloseCount": 103,
    "LogicConnectErrorCount": 0,
    "PhysicalConnectCount": 2,
    "PhysicalCloseCount": 0,
    "PhysicalConnectErrorCount": 0,
    "ExecuteCount": 102,
    "ErrorCount": 0,
    "CommitCount": 100,
    "RollbackCount": 0,
    "PSCacheAccessCount": 100,
    "PSCacheHitCount": 99,
    "PSCacheMissCount": 1,
    "StartTransactionCount": 100,
    "TransactionHistogram": [
      55,
      44,
      1,
      0,
      0,
      0,
      0
    ],
    "ConnectionHoldTimeHistogram": [
      53,
      47,
      3,
      0,
      0,
      0,
      0,
      0
    ],
    "RemoveAbandoned": false,
    "ClobOpenCount": 0,
    "BlobOpenCount": 0,
    "KeepAliveCheckCount": 0,
    "KeepAlive": false,
    "FailFast": false,
    "MaxWait": 1234,
    "MaxWaitThreadCount": -1,
    "PoolPreparedStatements": true,
    "MaxPoolPreparedStatementPerConnectionSize": 5,
    "MinEvictableIdleTimeMillis": 30001,
    "MaxEvictableIdleTimeMillis": 25200000,
    "LogDifferentThread": true,
    "RecycleErrorCount": 0,
    "PreparedStatementOpenCount": 1,
    "PreparedStatementClosedCount": 0,
    "UseUnfairLock": true,
    "InitGlobalVariants": false,
    "InitVariants": false
  }
]

IDE 提示支援

演示

克隆專案,執行test包內的DemoApplication

參考文章:https://github.com/alibaba/druid/blob/master/druid-spring-boot-starter/README.md