Spring Boot 2.x basis: the use of domestic database connection pool Druid

On one , we introduced Spring Boot in JDBC module automated configuration using default data source HikariCP. Then this section, we will introduce another widely used open source data source: Druid.

Druid is produced by Alibaba Division database open source projects. In addition it is a high performance database connection pool, is carrying a database connection pool monitoring. Although HikariCP has been very good, but for domestic users, may be more familiar with the Druid. So, how to use the Druid in Spring Boot is back-end developers need to master basic skills.

A data source configured Druid

Practice this section we will be based on : "Spring Boot 2.x based tutorial to access MySQL database using JdbcTemplate" code on the basis of a text. So, readers can code repository from the end of the text, the detection chapter3-1directory for the following hands-on learning.

Here we have to start configuring a data source for Spring Boot Druid project:

The first step : the pom.xmlintroduction of Spring Boot Starter package druid official offer.

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.21</version>
</dependency>
复制代码

Step Two : In application.propertiesconnection information in the configuration database.

Druid are arranged to spring.datasource.druidprefix, the configuration according to the previous, slightly modified to:

spring.datasource.druid.url=jdbc:mysql://localhost:3306/test
spring.datasource.druid.username=root
spring.datasource.druid.password=
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
复制代码

The third step : Druid connection pool configuration.

And Hikari as a data source to use good, we must make the appropriate configuration of its connection pool, such as the following:

spring.datasource.druid.initialSize=10
spring.datasource.druid.maxActive=20
spring.datasource.druid.maxWait=60000
spring.datasource.druid.minIdle=1
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=true
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxOpenPreparedStatements=20
spring.datasource.druid.validationQuery=SELECT 1
spring.datasource.druid.validation-query-timeout=500
spring.datasource.druid.filters=stat
复制代码

Description about each connection pool configuration Druid can be found in the following table:

Configuration The default value Explanation
name Configuring this attribute significance is that if multiple data sources exist to monitor when you can distinguish by area name. If no, will generate a name, the format is:. "DataSource-" + System.identityHashCode ( this) This property is additionally arranged at least in version 1.0.5 is inactive, an error will be forcibly set name. Details - click here .
url url connection to the database, different databases are not the same. For example: mysql: jdbc: mysql: //10.20.153.104: 3306 / druid2 oracle: jdbc: oracle: thin: @ 10.20.149.85: 1521: ocnauto
username User name to connect the database
password Password for the database connection. If you do not want to write code directly in the configuration file, you can use ConfigFilter. The details look here
driverClassName The automatic recognition url This feature can be a worthy, if not based on the configuration druid automatically identify dbType url, then select the appropriate driverClassName
initialSize 0 Establishing the number of physical connection initialization. Initialization occurs when the display call the init method, or the first getConnection
maxActive 8 The maximum number of connection pools
maxIdle 8 It is no longer used, equipped with no effect
minIdle The minimum number of connection pool
maxWait Acquires the maximum waiting time is connected, in milliseconds. After configuring maxWait, enabled by default fair locks, concurrent efficiency will decline, if necessary, by using the configuration useUnfairLock property to true unfair lock.
poolPreparedStatements false Whether the cache preparedStatement, which is PSCache. PSCache support database cursors huge performance boost, for example oracle. Under the proposed closure of mysql.
maxPoolPreparedStatementPerConnectionSize -1 To enable PSCache, must be greater than zero configuration, when greater than 0, poolPreparedStatements triggered automatically changed to true. In the Druid, the PSCache not exist too much memory for an Oracle issue, this value can be configured larger, such as 100
validationQuery For detecting whether a valid connection sql, a query is required, common select 'x'. If validationQuery is null, testOnBorrow, testOnReturn, testWhileIdle will not work.
validationQueryTimeout Unit: second detecting whether a valid connection timeout. void setQueryTimeout level calls jdbc Statement object (int seconds) Method
testOnBorrow true Execution validationQuery detect whether the connection is valid when applying for connection, made this configuration can degrade performance.
testOnReturn false Returned connection is valid execution validationQuery detect a connection, made this configuration can degrade performance.
testWhileIdle false Recommended configuration is true, does not affect performance, and ensure safety. Detecting when the application connection, if the idle time is greater than timeBetweenEvictionRunsMillis, performs detection validationQuery connection is valid.
keepAlive false (1.0.28) Number of connections within minIdle connection pool of idle time minEvictableIdleTimeMillis, keepAlive operation will be executed.
timeBetweenEvictionRunsMillis For 1 minute (1.0.14) It has two meanings: 1) detection interval Destroy thread connection, if the connection idle time is greater than or equal minEvictableIdleTimeMillis closes the physical connection. 2) testWhileIdle judgment basis, see detailed description of the property testWhileIdle
numTestsPerEvictionRun 30 minutes (1.0.14) 不再使用,一个DruidDataSource只支持一个EvictionRun
minEvictableIdleTimeMillis 连接保持空闲而不被驱逐的最小时间
connectionInitSqls 物理连接初始化的时候执行的sql
exceptionSorter 根据dbType自动识别 当数据库抛出一些不可恢复的异常时,抛弃连接
filters 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有: 监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall
proxyFilters 类型是List<com.alibaba.druid.filter.Filter>,如果同时配置了filters和proxyFilters,是组合关系,并非替换关系

到这一步,就已经完成了将Spring Boot的默认数据源HikariCP切换到Druid的所有操作。

配置Druid监控

既然用了Druid,那么对于Druid的监控功能怎么能不用一下呢?下面就来再进一步做一些配置,来启用Druid的监控。

第一步:在pom.xml中引入spring-boot-starter-actuator模块

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
复制代码

第二步:在application.properties中添加Druid的监控配置。

spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=true
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
复制代码

上面的配置主要用于开启stat监控统计的界面以及监控内容的相关配置,具体释意如下:

  • 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:监控页面的登录密码

第三步:针对之前实现的UserService内容,我们创建一个Controller来通过接口去调用数据访问操作:

@Data
@AllArgsConstructor
@RestController
public class UserController {

    private UserService userService;

    @PostMapping("/user")
    public int create(@RequestBody User user) {
        return userService.create(user.getName(), user.getAge());
    }

    @GetMapping("/user/{name}")
    public List<User> getByName(@PathVariable String name) {
        return userService.getByName(name);
    }

    @DeleteMapping("/user/{name}")
    public int deleteByName(@PathVariable String name) {
        return userService.deleteByName(name);
    }

    @GetMapping("/user/count")
    public int getAllUsers() {
        return userService.getAllUsers();
    }

    @DeleteMapping("/user/all")
    public int deleteAllUsers() {
        return userService.deleteAllUsers();
    }

}
复制代码

第四步:完成上面所有配置之后,启动应用,访问Druid的监控页面http://localhost:8080/druid/,可以看到如下登录页面:

img

输入上面spring.datasource.druid.stat-view-servlet.login-usernamespring.datasource.druid.stat-view-servlet.login-password配置的登录账户与密码,就能看到如下监控页面:

img

进入到这边时候,就可以看到对于应用端而言的各种监控数据了。这里讲解几个最为常用的监控页面:

数据源:这里可以看到之前我们配置的数据库连接池信息以及当前使用情况的各种指标。

img

SQL监控:该数据源中执行的SQL语句极其统计数据。在这个页面上,我们可以很方便的看到当前这个Spring Boot都执行过哪些SQL,这些SQL的执行频率和执行效率也都可以清晰的看到。如果你这里没看到什么数据?别忘了我们之前创建了一个Controller,用这些接口可以触发UserService对数据库的操作。所以,这里我们可以通过调用接口的方式去触发一些操作,这样SQL监控页面就会产生一些数据:

img

图中监控项上,执行时间、读取行数、更新行数都通过区间分布的方式表示,将耗时分布成8个区间:

  • 0 - 1 耗时0到1毫秒的次数
  • 1 - 10 耗时1到10毫秒的次数
  • 10 - 100 耗时10到100毫秒的次数
  • 100 - 1,000 耗时100到1000毫秒的次数
  • 1,000 - 10,000 耗时1到10秒的次数
  • 10,000 - 100,000 耗时10到100秒的次数
  • 100,000 - 1,000,000 耗时100到1000秒的次数
  • 1,000,000 - 耗时1000秒以上的次数

记录耗时区间的发生次数,通过区分分布,可以很方便看出SQL运行的极好、普通和极差的分布。 耗时区分分布提供了“执行+RS时分布”,是将执行时间+ResultSet持有时间合并监控,这个能方便诊断返回行数过多的查询。

SQL防火墙:该页面记录了与SQL监控不同维度的监控数据,更多用于对表访问维度、SQL防御维度的统计。

img

该功能数据记录的统计需要在spring.datasource.druid.filters中增加wall属性才会进行记录统计,比如这样:

spring.datasource.druid.filters=stat,wall
复制代码

注意:这里的所有监控信息是对这个应用实例的数据源而言的,而并不是数据库全局层面的,可以视为应用层的监控,不可能作为中间件层的监控。

代码示例

本文的相关例子可以查看下面仓库中的chapter3-3目录:

如果您觉得本文不错,欢迎Star支持,您的关注是我坚持的动力!

欢迎关注我的公众号:程序猿DD,获得独家整理的学习资源和日常干货推送。 如果您对我的专题内容感兴趣,也可以关注我的博客:didispace.com

Guess you like

Origin juejin.im/post/5e40ca33e51d4526dd1e96e8