Spring Boot & Druid

Druid 是一个 JDBC 组件库,包括数据库连接池、SQL Parser 等组件。

Spring Boot 中的使用方法

  1. 添加 Maven 依赖

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
    
  2. application.yml 中增加配置

    虽然官方文档上说只需要配置 spring.datasource 中的 uriusernamepassword 就行了,但是不配置 spring.datasource.druid 好像监控不到 SQL 的执行。
    有关配置项的含义请参照官方文档 配置_DruidDataSource 参考配置

    spring:
      datasource:
        name: DBRead
        url: jdbc:sqlserver://192.168.0.1:1433;databaseName=TEST_D
        username: sa
        password: sa
        # 使用 druid 数据源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
        filters: stat
        maxActive: 30
        initialSize: 2
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: true
        testOnReturn: true
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
        druid:
          initial-size: 2
          max-active: 30
          min-idle: 2
          max-wait: 60000
          pool-prepared-statements: true
          max-pool-prepared-statement-per-connection-size: 5
          #max-open-prepared-statements:  #等价于上面的 max-pool-prepared-statement-per-connection-size
          validation-query: select 1
          validation-query-timeout: 1
          test-on-borrow: true
          test-on-return: true
          test-while-idle: true
          time-between-eviction-runs-millis: 60000
          min-evictable-idle-time-millis: 300000
          async-close-connection-enable: true
          aop-patterns: octopus.cloud.user.controller.*
      jpa:
        showSql: true
    
  3. 获取 Druid 的监控数据

    @RestController
    public class DruidStatController {
        @GetMapping("/druid/stat")
        public Object druidStat(){
            // DruidStatManagerFacade#getDataSourceStatDataList 该方法可以获取所有数据源的监控数据,除此之外 DruidStatManagerFacade 还提供了一些其他方法,你可以按需选择使用。
            return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
        }
    }
    
  4. 启动后界面

    1. 首页
    2. 数据源
    3. SQL 监控
    4. SQL 防火墙
    5. Web 应用
    6. URI 监控
    7. Session 监控
    8. Spring 监控
    9. JSON API