文章目录
- 前言
- 一、启动器
- 二、配置
- 1.JDBC 配置
- 2.连接池配置
- 3. 监控配置
- 三、配置多数据源
- 1. 添加配置
- 2. 创建数据源
- 四、配置 Filter
- 1. 配置Filter
- 2. 可配置的Filter
- 五、获取 Druid 的监控数据
- 六、案例
- 1. 问题
- 2. 引入库
- 3. 配置
- 4. 配置类
- 5. 测试类
- 6. 测试结果
- 七、案例 ( 推荐 ) \color{#00FF00}{(推荐)} (推荐)
- 1. 引入库
- 2. 配置
- 3. 测试类
- 4. 测试结果
- 总结
前言
Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。
一、启动器
Druid Spring Boot Starter 用于帮助你在Spring Boot项目中轻松集成Druid数据库连接池和监控。
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.22</version>
</dependency>
二、配置
1.JDBC 配置
spring.datasource.druid.url= # 或spring.datasource.url=
spring.datasource.druid.username= # 或spring.datasource.username=
spring.datasource.druid.password= # 或spring.datasource.password=
spring.datasource.druid.driver-class-name= #或 spring.datasource.driver-class-name=
2.连接池配置
spring.datasource.druid.initial-size=
spring.datasource.druid.max-active=
spring.datasource.druid.min-idle=
spring.datasource.druid.max-wait=
spring.datasource.druid.pool-prepared-statements=
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=
spring.datasource.druid.max-open-prepared-statements= #和上面的等价
spring.datasource.druid.validation-query=
spring.datasource.druid.validation-query-timeout=
spring.datasource.druid.test-on-borrow=
spring.datasource.druid.test-on-return=
spring.datasource.druid.test-while-idle=
spring.datasource.druid.time-between-eviction-runs-millis=
spring.datasource.druid.min-evictable-idle-time-millis=
spring.datasource.druid.max-evictable-idle-time-millis=
spring.datasource.druid.filters= #配置多个英文逗号分隔
....//more
3. 监控配置
# WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
spring.datasource.druid.web-stat-filter.enabled= #是否启用StatFilter默认值false
spring.datasource.druid.web-stat-filter.url-pattern=
spring.datasource.druid.web-stat-filter.exclusions=
spring.datasource.druid.web-stat-filter.session-stat-enable=
spring.datasource.druid.web-stat-filter.session-stat-max-count=
spring.datasource.druid.web-stat-filter.principal-session-name=
spring.datasource.druid.web-stat-filter.principal-cookie-name=
spring.datasource.druid.web-stat-filter.profile-enable=
# StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置
spring.datasource.druid.stat-view-servlet.enabled= #是否启用StatViewServlet(监控页面)默认值为false(考虑到安全问题默认并未启动,如需启用建议设置密码或白名单以保障安全)
spring.datasource.druid.stat-view-servlet.url-pattern=
spring.datasource.druid.stat-view-servlet.reset-enable=
spring.datasource.druid.stat-view-servlet.login-username=
spring.datasource.druid.stat-view-servlet.login-password=
spring.datasource.druid.stat-view-servlet.allow=
spring.datasource.druid.stat-view-servlet.deny=
# Spring监控配置,说明请参考Druid Github Wiki,配置_Druid和Spring关联监控配置
spring.datasource.druid.aop-patterns= # Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔
三、配置多数据源
1. 添加配置
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
# Druid 数据源配置,继承spring.datasource.* 配置,相同则覆盖
...
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=5
...
# Druid 数据源 1 配置,继承spring.datasource.druid.* 配置,相同则覆盖
...
spring.datasource.druid.one.max-active=10
spring.datasource.druid.one.max-wait=10000
...
# Druid 数据源 2 配置,继承spring.datasource.druid.* 配置,相同则覆盖
...
spring.datasource.druid.two.max-active=20
spring.datasource.druid.two.max-wait=20000
...
2. 创建数据源
@Primary
@Bean
@ConfigurationProperties("spring.datasource.druid.one")
public DataSource dataSourceOne(){
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.druid.two")
public DataSource dataSourceTwo(){
return DruidDataSourceBuilder.create().build();
}
四、配置 Filter
1. 配置Filter
你可以通过 spring.datasource.druid.filters=stat,wall,log4j … 的方式来启用相应的内置Filter,不过这些Filter都是默认配置。如果默认配置不能满足你的需求,你可以放弃这种方式,通过配置文件来配置Filter,下面是例子。
# 配置StatFilter
spring.datasource.druid.filter.stat.enabled=true
spring.datasource.druid.filter.stat.db-type=h2
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000
# 配置WallFilter
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.db-type=h2
spring.datasource.druid.filter.wall.config.delete-allow=false
spring.datasource.druid.filter.wall.config.drop-table-allow=false
# 其他 Filter 配置不再演示
2. 可配置的Filter
目前为以下 Filter 提供了配置支持,请参考文档或者根据IDE提示(spring.datasource.druid.filter.*)进行配置。
- StatFilter
- WallFilter
- ConfigFilter
- EncodingConvertFilter
- Slf4jLogFilter
- Log4jFilter
- Log4j2Filter
- CommonsLogFilter
要想使自定义 Filter 配置生效需要将对应 Filter 的 enabled 设置为 true ,Druid Spring Boot Starter 默认禁用 StatFilter,你也可以将其 enabled 设置为 true 来启用它。
五、获取 Druid 的监控数据
Druid 的监控数据可以在开启 StatFilter 后通过 DruidStatManagerFacade 进行获取,获取到监控数据之后你可以将其暴露给你的监控系统进行使用。Druid 默认的监控系统数据也来源于此。下面给做一个简单的演示,在 Spring Boot 中如何通过 HTTP 接口将 Druid 监控数据以 JSON 的形式暴露出去,实际使用中你可以根据你的需要自由地对监控数据、暴露方式进行扩展。
@RestController
public class DruidStatController {
@GetMapping("/druid/stat")
public Object druidStat(){
// DruidStatManagerFacade#getDataSourceStatDataList 该方法可以获取所有数据源的监控数据,除此之外 DruidStatManagerFacade 还提供了一些其他方法,你可以按需选择使用。
return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
}
}
[
{
"Identity": 1583082378,
"Name": "DataSource-1583082378",
"DbType": "h2",
"DriverClassName": "org.h2.Driver",
"URL": "jdbc:h2:file:./demo-db",
"UserName": "sa",
"FilterClassNames": [
"com.alibaba.druid.filter.stat.StatFilter"
],
"WaitThreadCount": 0,
"NotEmptyWaitCount": 0,
"NotEmptyWaitMillis": 0,
"PoolingCount": 2,
"PoolingPeak": 2,
"PoolingPeakTime": 1533782955104,
"ActiveCount": 0,
"ActivePeak": 1,
"ActivePeakTime": 1533782955178,
"InitialSize": 2,
"MinIdle": 2,
"MaxActive": 30,
"QueryTimeout": 0,
"TransactionQueryTimeout": 0,
"LoginTimeout": 0,
"ValidConnectionCheckerClassName": null,
"ExceptionSorterClassName": null,
"TestOnBorrow": true,
"TestOnReturn": true,
"TestWhileIdle": true,
"DefaultAutoCommit": true,
"DefaultReadOnly": null,
"DefaultTransactionIsolation": null,
"LogicConnectCount": 103,
"LogicCloseCount": 103,
"LogicConnectErrorCount": 0,
"PhysicalConnectCount": 2,
"PhysicalCloseCount": 0,
"PhysicalConnectErrorCount": 0,
"ExecuteCount": 102,
"ErrorCount": 0,
"CommitCount": 100,
"RollbackCount": 0,
"PSCacheAccessCount": 100,
"PSCacheHitCount": 99,
"PSCacheMissCount": 1,
"StartTransactionCount": 100,
"TransactionHistogram": [
55,
44,
1,
0,
0,
0,
0
],
"ConnectionHoldTimeHistogram": [
53,
47,
3,
0,
0,
0,
0,
0
],
"RemoveAbandoned": false,
"ClobOpenCount": 0,
"BlobOpenCount": 0,
"KeepAliveCheckCount": 0,
"KeepAlive": false,
"FailFast": false,
"MaxWait": 1234,
"MaxWaitThreadCount": -1,
"PoolPreparedStatements": true,
"MaxPoolPreparedStatementPerConnectionSize": 5,
"MinEvictableIdleTimeMillis": 30001,
"MaxEvictableIdleTimeMillis": 25200000,
"LogDifferentThread": true,
"RecycleErrorCount": 0,
"PreparedStatementOpenCount": 1,
"PreparedStatementClosedCount": 0,
"UseUnfairLock": true,
"InitGlobalVariants": false,
"InitVariants": false
}
]
六、案例
1. 问题
在
1.2.13
快照版及之后的版本,都会去查找一个${project.version}
的属性导致我druid的包一直没有下载下来,
就算切换到之前的版本自动注入也无法生效,SpringBoot3是已经确定的大版本,所以我们只能放弃对start的使用。
<parent>
<groupId>com.alibaba</groupId>
<artifactId>druid-parent</artifactId>
<version>1.2.23-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>druid-spring-boot-3-starter</artifactId>
也可能是版本问题,官方的下一个版本
1.2.23-SNAPSHOT
,才能匹配springboot3版本。
2. 引入库
由于上面的问题,我们只能使用spring常规的使用方式,但是和mvc中可能会略有区别。
<properties>
<java.version>17</java.version>
<spring.version>6.1.6</spring.version>
<springboo.version>3.2.5</springboo.version>
</properties>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.22</version>
</dependency>
3. 配置
spring:
application:
name: spring-boot3
#druid
datasource:
#type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
username: root
password: 123456a?
initial-size: 5
max-active: 20
max-wait: 60000
min-idle: 3
4. 配置类
package org.example.springboot3.druid.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* Create by zjg on 2024/5/19
*/
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid")
public DataSource dataSource(){
return new DruidDataSource();
}
}
5. 测试类
package org.example.springboot3.druid.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Create by zjg on 2024/5/19
*/
@RestController
@RequestMapping("/druid/")
public class DruidController {
@Autowired
DataSource dataSource;
@RequestMapping("001")
public String druid001() throws SQLException {
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select 1 from dual");
String result = null;
if(resultSet.next()){
result=resultSet.getString(1);
}
statement.close();connection.close();
return result;
}
}
6. 测试结果
1
单独使用最新的
1.2.22
版本是没有问题的。
七、案例 ( 推荐 ) \color{#00FF00}{(推荐)} (推荐)
昨天写了这篇文章之后,感觉没有把最好的带给家人们,经过一晚上的不断阅读诸佬的经典,总算找到了druid对springboot支持的starter,可能是阿里的哥哥们太忙了,官方文档是一点介绍没有啊!
1. 引入库
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-3-starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-3-starter</artifactId>
<version>1.2.22</version>
</dependency>
2. 配置
spring:
application:
name: spring-boot3
#druid
datasource:
#type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
username: root
password: 123456a?
initial-size: 5
max-active: 20
max-wait: 60000
min-idle: 3
3. 测试类
package org.example.springboot3.druid.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Create by zjg on 2024/5/19
*/
@RestController
@RequestMapping("/druid/")
public class DruidController {
@Autowired
DataSource dataSource;
@RequestMapping("001")
public String druid001() throws SQLException {
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select 1 from dual");
String result = null;
if(resultSet.next()){
result=resultSet.getString(1);
}
statement.close();connection.close();
return result;
}
}
4. 测试结果
1
总结
回到顶部
源码仓库
中文文档
Druid Spring Boot Starter
更多内容请参考:
【第5章】spring命名空间和数据源的引入
【第21章】spring-mvc之整合druid
推荐大家使用starter的案例。