SpringBoot中整合Druid数据库连接池

Druid数据库连接池

简介

Druid是Ali推出的一款开源数据库连接池,其号称是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。

通过Maven快速开始

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>${druid-version}</version>
</dependency>

在SpringBoot我们也可以使用官方提供的starter快速使用,不用进行复杂的配置

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

配置YML

在这里我们使用的是官方所提供的druid-spring-boot-starter

server:
  port: 8080
  servlet:
    context-path: /st
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/boot2?serverTimezone=GMT&useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: 123456
    platform: mysql
    druid:
    # 初始化大小,最小,最大
      initial-size: 5
      min-idle: 5
      maxActive: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall
      maxPoolPreparedStatementPerConnectionSize: 20
      useGlobalDataSourceStat: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
      # statViewServlet配置,说明配置参考druid wiki
      stat-view-servlet:
        # 是否启用statViewServlet配置
        enabled: true
        # 访问监控页面
        url-pattern: "/druid/*"
        # 禁止手动重置监控数据
        reset-enable: false
        # 设置监控页面的登陆名
        login-username: admin
        # 设置监控页面的登陆密码
        login-password: 123456
        #WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
      web-stat-filter:
        # 是否启用WebStatFilter
        enabled: true
        # 访问路径
        url-pattern: "/*"
        # 排除不必要的url
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
        # 监控最大session数,默认是1000
        session-stat-max-count: 1000
        # 是否启用session的统计功能
        session-stat-enable: true
        # 是否启用监控单个Url调用的sql列表
        profile-enable: true
        # 使druid当前session的用户是谁,session_user_key是你保存到session中的sessionName
        principalSessionName: session_user_key
        # 使druid只当当前的user是谁,cookie_user_key是你保存在cookie中的cookieName
        principalCookieName: cookie_user_key

监控View


本作品采用知识共享署名 4.0 国际许可协议进行许可。

如果可以的话,请给我钱请给我点赞赏,小小心意即可!

Last modification:September 12, 2019
If you think my article is useful to you, please feel free to appreciate