Spring Boot 数据库连接池 HikariCP

1、HikariCP?

HikariCP 来源于日语,「光」的意思,意味着它很快!spring boot2.0 已经将 HikariCP 做为了默认的数据源链接池。
官网详细地说明了HikariCP所做的一些优化,总结如下:

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

2、数据库连接池

所有数据库链接池都遵守基本的设计规则,实现 javax.sql.DataSource 接口,里面最重要的方法就是
getConnection() ,用于获取一个Connection, 一个Connection就是一个数据库链接。数据库链接池通过事先建立好
Connection 并缓存起来,这样应用需要做数据查询的时候,直接从缓存中拿到 Connection
就可以使用来。数据库链接池还能够检测异常的链接,释放闲置的链接。

3、常用属性配置

3.1 autoCommit

This property controls the default auto-commit behavior of connections
returned from the pool. It is a boolean value. Default: true
此属性控制从池返回的连接的默认自动提交行为, 它是一个布尔值。 默认值:true

3.2 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秒)

3.3 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分钟)

3.4 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分钟)

3.5 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将记录错误以通知您。 默认值:无

3.6 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 相同

3.7 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

3.9 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 的实例来记录各种度量标准。 有关详细信息,请参阅度量维基页面。 默认值:无

3.10 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 的实例来报告当前的健康信息。 有关详细信息,请参阅运行状况检查维基页面。
默认值:无

3.11 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 管理控制台中,以标识池和池配置。 默认值:自动生成

4、配置示例

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/foo-dev?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root 
spring.datasource.password=fm*****
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

5、可选配置

############################################################
#
# 配置数据源信息
#
############################################################
spring:
  #profiles:
  #  active: dev
  datasource:                                           # 数据源的相关配置
    type: com.zaxxer.hikari.HikariDataSource          # 数据源类型:HikariCP
    driver-class-name: com.mysql.cj.jdbc.Driver        # mysql8驱动  com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/foo-dev?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
    username: root
    password: fm*********
    hikari:
      connection-timeout: 30000       # 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 默认:30秒
      minimum-idle: 5                 # 最小连接数
      maximum-pool-size: 20           # 最大连接数
      auto-commit: true               # 自动提交
      idle-timeout: 600000            # 连接超时的最大时长(毫秒),超时则被释放(retired),默认:10分钟
      pool-name: DateSourceHikariCP     # 连接池名字
      max-lifetime: 1800000           # 连接的生命时长(毫秒),超时而且没被使用则被释放(retired),默认:30分钟 1800000ms
      connection-test-query: SELECT 1

5、性能方面

有兴趣的可以自行尝试测试。

  • 性能方面 hikariCP>druid>tomcat-jdbc>dbcp>c3p0 。hikariCP的高性能得益于最大限度的避免锁竞争。
  • druid功能最为全面,sql拦截等功能,统计数据较为全面,具有良好的扩展性。

6、功能对比参照

在这里插入图片描述
线程的作用

dbcp:一个线程:负责心跳,最小连接数维持,最大空闲时间和防连接泄露。
druid: 两个线程: 其中一个负责异步创建。一个负责最小连接数的维持。 其中心跳是通过获取连接,来判定是否小于心跳间隔。
hikariCP: 三个线程: 其中一个为定时线程,解决最大空闲时间。两个为新建连接和关闭连接。 均是连接池,空闲5s,线程便会关闭。
c3p0: 四个线程;三个helperThread (pollerThread),一个定时
proxool网上有说在并发较高的情况下会出错,在此没有进行研究。
druid的功能比较全面,且扩展性较好,比较方便对jdbc接口进行监控跟踪等。
c3p0历史悠久,代码及其复杂,不利于维护。并且存在潜在的风险。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值