1. Create a new springboot project
2. druid learning address
https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
3. Import druid related dependencies
<!--druid相关依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
4. Modify application.yml and add druid related configuration in the application.yml file
The default data source of springboot is org.apache.tomcat.jdbc.pool.DataSource
#数据库连接池druid配置
spring:
datasource:
#1.JDBC
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/t263?useUnicode=true&characterEncoding=UTF-8
username: root
password: 123
druid:
#2.连接池配置
#初始化连接池的连接数量 大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
#配置获取连接等待超时的时间
max-wait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 30000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: true
test-on-return: false
# 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
#3.基础监控配置
web-stat-filter:
enabled: true
url-pattern: /*
#设置不统计哪些URL
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
session-stat-enable: true
session-stat-max-count: 100
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
#设置监控页面的登录名和密码
login-username: admin
login-password: admin
allow: 127.0.0.1
Note: The version my mysql uses here is 5.1.44, so my driver-class-name and url will be different from those who use the latest version (such as mysql8.0). If the mysql version is relatively high, then configure as follows:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/t263?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC
5. Start the springboot project to access druid, visit http://localhost:tomcat port number/project name/druid/
The login name and password here, we can find admin and admin in application.yml, after login, there will be the following interface, which means that our druid connection pool has been successfully added~