天天看點

Spring Boot 資料庫連接配接池 HikariCP1、HikariCP?2、資料庫連接配接池3、常用屬性配置4、配置示例5、可選配置5、性能方面6、功能對比參照

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、功能對比參照

Spring Boot 資料庫連接配接池 HikariCP1、HikariCP?2、資料庫連接配接池3、常用屬性配置4、配置示例5、可選配置5、性能方面6、功能對比參照

線程的作用

dbcp:一個線程:負責心跳,最小連接配接數維持,最大空閑時間和防連接配接洩露。
druid: 兩個線程: 其中一個負責異步建立。一個負責最小連接配接數的維持。 其中心跳是通過擷取連接配接,來判定是否小于心跳間隔。
hikariCP: 三個線程: 其中一個為定時線程,解決最大空閑時間。兩個為建立連接配接和關閉連接配接。 均是連接配接池,空閑5s,線程便會關閉。
c3p0: 四個線程;三個helperThread (pollerThread),一個定時
proxool網上有說在并發較高的情況下會出錯,在此沒有進行研究。
druid的功能比較全面,且擴充性較好,比較友善對jdbc接口進行監控跟蹤等。
c3p0曆史悠久,代碼及其複雜,不利于維護。并且存在潛在的風險。