简述: 记录在学习SpringBoot是整合Druid所遇到的坑。

本文初发于 “曾晨de小站” zengchen233.cn,同步转载于此。

在学习狂神说SpringBoot时有一处在自动注入DataSource时,总是爆红,在到处查询后记录如下:

首先需要在pom中引入

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

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

application.yaml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: zengchen
    password: zengchen233
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      # 初始连接数
      initial-size: 5
      # 最小连接池数量
      min-idle: 10
      # 最大连接数量
      max-active: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      # 配置一个连接在池中最大生存的时间,单位是毫秒
      maxEvictableIdleTimeMillis: 900000
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,wall用于防火墙
      filters: stat,wall,log4j
      # 合并多个DruidDatasource的监控数据
      useGlobalDataSourceStat: true
      #通过connectProperties属性来打开mergeSql功能 慢Sql记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500;
      # 开启网页监控
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: false
        login-username: druid
        login-password: druid