第三节 SpringBoot集成Druid 数据库连接池

亮子 2022-09-16 08:46:39 10471 0 0 0

1、引入依赖

  • 最高版本
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.6</version>
</dependency>
  • 使用版本
        <!--阿里的数据库连接池-->
        <!--https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.22</version>
        </dependency>

2、修改配置文件

## 服务信息
spring.application.name=demo-druid-0830
server.port=9090

## mybatis and mybatis plus
spring.datasource.url=jdbc:mysql://localhost:3306/db_shenma_blog?autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
mybatis.typeAliasesPackage=com.shenmazong.demodruid0830.mapper
mybatis.mapperLocations=classpath:/mapper/*.xml
logging.level.com.shenmazong.demodruid0830.mapper=debug

## 阿里巴巴的数据库连接池
# http://localhost:9000/druid/login.html
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=5
spring.datasource.druid.min-idle=5
spring.datasource.druid.maxActive=20
spring.datasource.druid.maxWait=60000
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.druid.filters=stat,wall,log4j2
spring.datasource.druid.connectionProperties=druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*

# 1.1.10以后的版本需要指定为true 不然默认是关闭的就会出现404
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
#spring.datasource.druid.stat-view-servlet.allow=127.0.0.1,*
#spring.datasource.druid.stat-view-servlet.deny=192.168.1.73
spring.datasource.druid.stat-view-servlet.reset-enable=false
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=123456

3、连接池管理首页

  • 性能监控
# 访问地址
http://localhost:9000/druid/
  • 连接池管理首页

img

  • 连接池SQL健康

img

4、增加慢查询阈值

# 文件application.properties 中 添加
# 慢查询 超过1毫秒就是
# 是否需要数据库的支持呢?不需要
spring.datasource.druid.filters=stat
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=1

参考文章