转载

Spring Boot中使用HikariCP连接池

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'

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'
}

配置文件如下:

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 。

示例代码如下:

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

/**
	 * 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中加入如下依赖:

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的配置:

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 当即生效。

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
正文到此结束
Loading...