SpringBoot从入门到精通教程(十四)- Druid连接池集成

需求背景

Springboot集成Druid连接池集成,来自阿里的数据库连接池,Druid加入了日志监控,可以很好的监控DB池连接和SQL的执行情况等。

代码演示

此项目在教程:SpringBoot从入门到精通教程(六)- Mysql和Mybatis+XML用法详解的基础上改造的

1. 引入Druid最新maven依赖

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

2. application.yml文件配置,配置Druid。多数据源项目时,用法同理SpringBoot从入门到精通教程(七)- 多数据源用法

spring:
   datasource:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/cfdb?useUnicode=true&autoReconnect=true&allowMultiQueries=true&useSSL=false
      username: root
      password: a123456
      # 使用alibaba的druid连接池、监控
      type: com.alibaba.druid.pool.DruidDataSource
      druid:
         max-active: 10
         max-wait: 5000
         min-idle: 5
         initial-size: 2
         validation-query: SELECT 1
         test-on-borrow: false
         test-while-idle: true
         time-between-eviction-runs-millis: 18800
         web-stat-filter:
            enabled: true
            exclusions: js,gif,jpg,png,css,ico,/druid/*
         stat-view-servlet:
            enabled: true
            login-username: druid
            login-password: druid@2019
server:
   port: 9090
mybatis:
   config-location: classpath:mybatis-config.xml

注意:这里是配置druid web访问界面的账号的密码

stat-view-servlet:
    enabled: true
    login-username: druid
    login-password: druid@2019

3. 启动项目

启动日志中,可以看到Druid已成功加载

4. 分别访问接口,Druid会监控到的

http://localhost:9090/hello

http://localhost:9090/listCities

http://localhost:9090/getCityById?id=1

5. 登录Druid管理控制界面

访问地址:http://localhost:9090/druid/,输入前面配置的账号名和密码,即可登录

登录成功:

案例说明

SQL监控界面

可以看得到sql执行的相关数据,比如次数、执行时间等

URL监控界面

可以看得到接口访问的相关数据,比如接口名、请求次数、请求时间等

其他相关功能,可以自行摸索了

完整源码下载

我的Github源码地址:

https://github.com/hemin1003/spring-boot-study/tree/master/spring-boot2-study/spring-boot2-parent/spring-boot2-mysql-druid

该系列教程

SpringBoot系列

至此,全部介绍就结束了

------------------------------------------------------

------------------------------------------------------

关于我(个人域名)

我的开源项目集Github

期望和大家一起学习,一起成长,共勉,O(∩_∩)O谢谢

欢迎交流问题,可加个人QQ 469580884,

或者,加我的群号 751925591,一起探讨交流问题

不讲虚的,只做实干家

Talk is cheap,show me the code

发布了220 篇原创文章 · 获赞 232 · 访问量 65万+

猜你喜欢

转载自blog.csdn.net/hemin1003/article/details/99637453