Spring Boot 数据库连接池 HikariCP

简介

HikariCP 来源于日语,「光」的意思,意味着它很快!可靠的数据源,spring boot2.0 已经将 HikariCP 做为了默认的数据源链接池。

官网详细地说明了HikariCP所做的一些优化,总结如下:

  • 字节码精简 :优化代码,直到编译后的字节码最少,这样,CPU缓存可以加载更多的程序代码;
  • 优化代理和拦截器:减少代码,例如 HikariCP 的 Statement proxy 只有 100 行代码,只有BoneCP 的十分之一;
  • 自定义数组类型(FastStatementList)代替 ArrayList:避免每次 get() 调用都要进行 range check,避免调用 remove() 时的从头到尾的扫描;
  • 自定义集合类型(ConcurrentBag):提高并发读写的效率;

详细的介绍,可阅读【追光者系列】Springboot 2.0选择HikariCP作为默认数据库连接池的五大理由

数据库连接池

所有数据库链接池都遵守基本的设计规则,实现 javax.sql.DataSource 接口,里面最重要的方法就是 Connection getConnection() throws SQLException; 用于获取一个Connection, 一个Connection就是一个数据库链接,就是一个TCP链接,建立TCP链接是需要进行3次握手的,这降低来链接的使用效率,也是各种数据库链接池存在的原因。

数据库链接池通过事先建立好 Connection 并缓存起来,这样应用需要做数据查询的时候,直接从缓存中拿到 Connection 就可以使用来。数据库链接池还能够检测异常的链接,释放闲置的链接。

B站-Java高级进阶精讲之高并发技术之理解数据库连接池的原理与实现 介绍了数据库连接池的概念,自己手动实现了一个简易的数据库连接池,虽然比较啰嗦,但是还是有内容的

常用属性配置

如下属性都不是必须的,属于可选配置

autoCommit

This property controls the default auto-commit behavior of connections returned from the pool. It is a boolean value. Default: true

此属性控制从池返回的连接的默认自动提交行为。 它是一个布尔值。 默认值:true

connectionTimeout

This property controls the maximum number of milliseconds that a client (that's you) will wait for a connection from the pool. If this time is exceeded without a connection becoming available, a SQLException will be thrown. Lowest acceptable connection timeout is 250 ms. Default: 30000 (30 seconds)

此属性控制客户端(即您)等待池中连接的最大毫秒数。 如果在没有连接可用的情况下超过此时间,则将抛出 SQLException。 最低可接受的连接超时为 250 毫秒。 默认值:30000(30秒)

idleTimeout

This property controls the maximum amount of time that a connection is allowed to sit idle in the pool. This setting only applies when minimumIdle is defined to be less than maximumPoolSize. Idle connections will not be retired once the pool reaches minimumIdle connections. Whether a connection is retired as idle or not is subject to a maximum variation of +30 seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout. A value of 0 means that idle connections are never removed from the pool. The minimum allowed value is 10000ms (10 seconds). Default: 600000 (10 minutes)

此属性控制允许连接在池中空闲的最长时间。 此设置仅在 minimumIdle 定义为小于maximumPoolSize 时适用。 一旦池达到 minimumIdle 连接,空闲连接将不会退出。 连接是否空闲退出的最大变化为 +30 秒,平均变化为 +15 秒。 在此超时之前,连接永远不会被空闲。 值为 0 表示永远不会从池中删除空闲连接。 允许的最小值为 10000 毫秒(10秒)。 默认值:600000(10分钟)

maxLifetime

This property controls the maximum lifetime of a connection in the pool. An in-use connection will never be retired, only when it is closed will it then be removed. On a connection-by-connection basis, minor negative attenuation is applied to avoid mass-extinction in the pool. We strongly recommend setting this value, and it should be several seconds shorter than any database or infrastructure imposed connection time limit. A value of 0 indicates no maximum lifetime (infinite lifetime), subject of course to the idleTimeout setting. Default: 1800000 (30 minutes)

此属性控制池中连接的最长生命周期。 使用中的连接永远不会退役,只有当它关闭时才会被删除。 在逐个连接的基础上,应用轻微的负衰减以避免池中的大量灭绝。 我们强烈建议设置此值,它应比任何数据库或基础结构强加的连接时间限制短几秒。 值 0 表示没有最大生命周期(无限生命周期),当然主题是 idleTimeout 设置。 默认值:1800000(30分钟)

connectionTestQuery

If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" drivers that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none

如果您的驱动程序支持JDBC4,我们强烈建议您不要设置此属性。 这适用于不支持 JDBC4 Connection.isValid()API 的“遗留”驱动程序。 这是在从池中给出连接之前执行的查询,以验证与数据库的连接是否仍然存在。 再次尝试运行没有此属性的池,如果您的驱动程序不符合JDBC4,HikariCP将记录错误以通知您。 默认值:无

minimumIdle

This property controls the minimum number of idle connections that HikariCP tries to maintain in the pool. If the idle connections dip below this value and total connections in the pool are less than maximumPoolSize, HikariCP will make a best effort to add additional connections quickly and efficiently. However, for maximum performance and responsiveness to spike demands, we recommend not setting this value and instead allowing HikariCP to act as a fixed size connection pool. Default: same as maximumPoolSize

此属性控制 HikariCP 尝试在池中维护的最小空闲连接数。 如果空闲连接低于此值并且池中的总连接数小于 maximumPoolSize,则 HikariCP 将尽最大努力快速有效地添加其他连接。 但是,为了获得最高性能和对峰值需求的响应,我们建议不要设置此值,而是允许 HikariCP 充当固定大小的连接池。 默认值:与 maximumPoolSize 相同

maximumPoolSize

This property controls the maximum size that the pool is allowed to reach, including both idle and in-use connections. Basically this value will determine the maximum number of actual connections to the database backend. A reasonable value for this is best determined by your execution environment. When the pool reaches this size, and no idle connections are available, calls to getConnection() will block for up to connectionTimeout milliseconds before timing out. Please read about pool sizing. Default: 10

此属性控制允许池到达的最大大小,包括空闲和正在使用的连接。 基本上,此值将确定数据库后端的最大实际连接数。 对此的合理值最好由您的执行环境决定。 当池达到此大小,并且没有可用的空闲连接时,对 getConnection() 的调用将在超时前阻塞最多 connectionTimeout 毫秒。 请阅读有关游泳池尺寸的信息。 默认值:10

metricRegistry

This property is only available via programmatic configuration or IoC container. This property allows you to specify an instance of a Codahale/Dropwizard MetricRegistry to be used by the pool to record various metrics. See the Metrics wiki page for details. Default: none

此属性仅可通过编程配置或 IoC 容器获得。 此属性允许您指定池使用的 Codahale / Dropwizard MetricRegistry 的实例来记录各种度量标准。 有关详细信息,请参阅度量维基页面。 默认值:无

healthCheckRegistry

This property is only available via programmatic configuration or IoC container. This property allows you to specify an instance of a Codahale/Dropwizard HealthCheckRegistry to be used by the pool to report current health information. See the Health Checks wiki page for details. Default: none

此属性仅可通过编程配置或IoC容器获得。 此属性允许您指定池使用的 Codahale / Dropwizard HealthCheckRegistry 的实例来报告当前的健康信息。 有关详细信息,请参阅运行状况检查维基页面。 默认值:无

poolName

This property represents a user-defined name for the connection pool and appears mainly in logging and JMX management consoles to identify pools and pool configurations. Default: auto-generated

此属性表示连接池的用户定义名称,主要显示在日志记录和 JMX 管理控制台中,以标识池和池配置。 默认值:自动生成

配置示例

Spring Boot 2.0 默认连接池就是 Hikari 了,所以引用 parents 后不用专门加依赖

  • Spring Boot 2.x 默认使用 HikariCP
  • Spring Boot 1.x 默认使用的是 Tomcat 连接池,需要移除 tomcat-jdbc,配置 spring.datasource.type=com.zaxxer.hikari.hIkari.HikariDatasource

例如:

spring.datasource.url=jdbc:mysql://localhost:3306/beta?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=cicd
spring.datasource.password=Home123*
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# 可选配置
spring.datasource.type=com.zaxxer.hikari.hIkari.HikariDatasource
spring.datasource.hikari.minimumIdle=10

# Hikari连接池的设置
## Hikari 时间单位都是毫秒
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
## 连接池名字
spring.datasource.hikari.pool-name=MyHikariCP
## 最小空闲连接数量
spring.datasource.hikari.minimum-idle=10
## 空闲连接存活最大时间,默认600000(10分钟)
spring.datasource.hikari.idle-timeout=600000
## 连接池最大连接数,默认是10
spring.datasource.hikari.maximum-pool-size=10
## 此属性控制从池返回的连接的默认自动提交行为,默认值:true
spring.datasource.hikari.auto-commit=true
## 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
spring.datasource.hikari.max-lifetime=1800000
## 数据库连接超时时间,默认30秒,即30000
spring.datasource.hikari.connection-timeout=30000

访问链接可以看到 acutator 监控数据:

代码示例

FAQ

【追光者系列】Hikari连接池配多大合适?

参考

posted @ 2019-04-22 00:27  Michael翔  阅读(23965)  评论(0编辑  收藏  举报