Spring Boot如何使用HikariCP连接池详解

时间:2022-10-08 19:10:56

前言

springboot让java开发更加美好,更加简洁,更加简单。spring boot 2.x中使用hikaricp作为默认的数据连接池。 hikaricp使用javassist字节码操作库来实现动态代理,优化并精简了字节码,同时内部使用 com.zaxxer.hikari.util.fastlist 代替arraylist、使用了更好的并发集合类 com.zaxxer.hikari.util.concurrentbag ,“号称”是目前最快的数据库连接池。

下面话不多说了,来一起看看详细的介绍吧

基本使用

在spring boot 2.x中使用hikaricp十分简单,只需引入依赖 implementation 'org.springframework.boot:spring-boot-starter-jdbc'

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
pluginmanagement {
    repositories {
        gradlepluginportal()
    }
}
rootproject.name = 'datasource-config'
 
plugins {
    id 'org.springframework.boot' version '2.1.3.release'
    id 'java'
}
 
apply plugin: 'io.spring.dependency-management'
 
group = 'spring-boot-guides'
version = '0.0.1-snapshot'
sourcecompatibility = '1.8'
 
repositories {
    mavencentral()
}
 
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    runtimeonly 'com.h2database:h2'
    testimplementation 'org.springframework.boot:spring-boot-starter-test'
}

配置文件如下:

?
1
2
3
4
5
6
7
8
9
10
11
spring:
 datasource:
 url: jdbc:h2:mem:demodb
 username: sa
 password:
 hikari: # https://github.com/brettwooldridge/hikaricp (uses milliseconds for all time values)
 maximumpoolsize: 10
 minimumidle: 2
 idletimeout: 600000
 connectiontimeout: 30000
 maxlifetime: 1800000

关于连接池的具体配置参数详见 hikaricp

示例代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package springbootguides.datasourceconfig;
 
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.commandlinerunner;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
 
import javax.sql.datasource;
import java.sql.connection;
 
@springbootapplication
public class datasourceconfigapplication implements commandlinerunner {
 
    @autowired
    private datasource datasource;
 
    @override
    public void run(string... args) throws exception {
        try(connection conn = datasource.getconnection()) {
            system.out.println(conn);
        }
    }
 
    public static void main(string[] args) {
        springapplication.run(datasourceconfigapplication.class, args);
    }
 
}

实现原理

spring boot使用如下方式整合hikaricp:入口是 org.springframework.boot.autoconfigure.jdbc.datasourceautoconfiguration ,通过 org.springframework.boot.autoconfigure.jdbc.datasourceconfiguration.hikari 中的 @bean 方式创建 com.zaxxer.hikari.hikaridatasource

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
     * hikari datasource configuration.
     */
    @conditionalonclass(hikaridatasource.class)
    @conditionalonmissingbean(datasource.class)
    @conditionalonproperty(name = "spring.datasource.type", havingvalue = "com.zaxxer.hikari.hikaridatasource", matchifmissing = true)
    static class hikari {
 
        @bean
        @configurationproperties(prefix = "spring.datasource.hikari")
        public hikaridatasource datasource(datasourceproperties properties) {
            hikaridatasource datasource = createdatasource(properties,
                    hikaridatasource.class);
            if (stringutils.hastext(properties.getname())) {
                datasource.setpoolname(properties.getname());
            }
            return datasource;
        }
 
    }

@configurationproperties(prefix = "spring.datasource.hikari") 会自动把 spring.datasource.hikari.* 相关的连接池配置信息注入到创建的hikaridatasource实例中。

hikaricp的监控和遥测

因为在我们的微服务体系中使用的监控系统是prometheus,这里以prometheus为例。

注意spring boot 2.0对spring boot 1.x的metrics进行了重构,不再向后兼容,主要是在spring-boot-acutator中使用了micrometer,支持了更多的监控系统:atlas、datadog、ganglia、graphite、influx、jmx、newrelic、prometheus、signalfx、statsd、wavefront。spring boot 2.0的metrics对比spring boot 1.x除了引入micrometer外,更大的体现是支持了tag,这也说明prometheus、influx等支持tag的时序监控数据模型的监控系统已经成为主流。

在前面示例中的build.gradle中加入如下依赖:

?
1
2
3
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.micrometer:micrometer-registry-prometheus'

配置文件applycation.yaml中加入对actuator的配置:

?
1
2
3
4
5
6
7
8
9
management:
 endpoints:
 web:
  exposure:
  include: "health,info,prometheus"
 server:
 port: 8079
 servlet:
  context-path: /

注意这里引入了web和actuator依赖,通过配置 management.server.port 指定actuator的web端点为8089端口,通过 management.endpoints.include 对外开放 /actuator/prometheus ,在引入 io.micrometer:micrometer-registry-prometheus 依赖之后,端点 /actuator/prometheus 当即生效。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
curl http://localhost:8079/actuator/prometheus | grep hikari
# type hikaricp_connections_acquire_seconds summary
hikaricp_connections_acquire_seconds_count{pool="hikaripool-1",} 3.0
hikaricp_connections_acquire_seconds_sum{pool="hikaripool-1",} 0.001230082
# help hikaricp_connections_acquire_seconds_max connection acquire time
# type hikaricp_connections_acquire_seconds_max gauge
hikaricp_connections_acquire_seconds_max{pool="hikaripool-1",} 0.0
# help hikaricp_connections_min min connections
# type hikaricp_connections_min gauge
hikaricp_connections_min{pool="hikaripool-1",} 2.0
# type hikaricp_connections_timeout_total counter
hikaricp_connections_timeout_total{pool="hikaripool-1",} 0.0
# help hikaricp_connections_pending pending threads
# type hikaricp_connections_pending gauge
hikaricp_connections_pending{pool="hikaripool-1",} 0.0
# help hikaricp_connections_usage_seconds connection usage time
# type hikaricp_connections_usage_seconds summary
hikaricp_connections_usage_seconds_count{pool="hikaripool-1",} 3.0
hikaricp_connections_usage_seconds_sum{pool="hikaripool-1",} 0.06
# help hikaricp_connections_usage_seconds_max connection usage time
# type hikaricp_connections_usage_seconds_max gauge
hikaricp_connections_usage_seconds_max{pool="hikaripool-1",} 0.0
# help hikaricp_connections_max max connections
# type hikaricp_connections_max gauge
hikaricp_connections_max{pool="hikaripool-1",} 10.0
# help hikaricp_connections total connections
# type hikaricp_connections gauge
hikaricp_connections{pool="hikaripool-1",} 2.0
# help hikaricp_connections_creation_seconds_max connection creation time
# type hikaricp_connections_creation_seconds_max gauge
hikaricp_connections_creation_seconds_max{pool="hikaripool-1",} 0.0
# help hikaricp_connections_creation_seconds connection creation time
# type hikaricp_connections_creation_seconds summary
hikaricp_connections_creation_seconds_count{pool="hikaripool-1",} 1.0
hikaricp_connections_creation_seconds_sum{pool="hikaripool-1",} 0.001
# help hikaricp_connections_idle idle connections
# type hikaricp_connections_idle gauge
hikaricp_connections_idle{pool="hikaripool-1",} 2.0
# help hikaricp_connections_active active connections
# type hikaricp_connections_active gauge
hikaricp_connections_active{pool="hikaripool-1",} 0.0

参考

hikaricp

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。

原文链接:http://blog.frognew.com/2019/02/spring-boot-guides-hikari.html