Spring Boot How to Use HikariCP Connection Pool

  • 2021-07-03 00:13:11
  • OfStack

Preface

Springboot makes Java development better, simpler and simpler. HikariCP is used as the default data connection pool in Spring Boot 2. x. HikariCP uses Javassist ByteCode manipulation library to implement dynamic proxy, optimize and streamline ByteCode, and use com.zaxxer.hikari.util.FastList Instead of ArrayList, a better concurrent collection class is used com.zaxxer.hikari.util.ConcurrentBag "Claims" is currently the fastest database connection pool.

The following words are not much to say, let's take a look at the detailed introduction

Basic use

Using HikariCP 10 in Spring Boot 2. x is simple and requires only the introduction of dependencies 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'
}

The configuration file is as follows:


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

See HikariCP for specific configuration parameters of connection pool.

The sample code is as follows:


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);
	}

}

Implementation principle

Spring Boot integrates HikariCP in the following way: The entry is org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration , through org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.Hikari Created by @ Bean in 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") Will automatically put spring.datasource.hikari.* Related connection pool configuration information is injected into the created HikariDataSource instance.

Monitoring and Telemetry of HikariCP

Because the monitoring system used in our micro-service system is Prometheus, take Prometheus as an example.

Note that spring boot 2.0 reconstructs metrics of spring boot 1. x and is no longer backward compatible. micrometer is mainly used in spring-boot-acutator, which supports more monitoring systems: Atlas, Datadog, Ganglia, Graphite, Influx, JMX, NewRelic, Prometheus, SignalFx, StatsD and Wavefront. Compared with spring boot 1. x, metrics of Spring boot 2.0 not only introduces micrometer, but also supports tag, which also shows that Prometheus, Influx and other monitoring systems supporting Tag timing monitoring data model have become mainstream.

Add the following dependencies to build. gradle in the previous example:


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

Add the configuration for actuator to the configuration file applycation. yaml:


management:
 endpoints:
 web:
  exposure:
  include: "health,info,prometheus"
 server:
 port: 8079
 servlet:
  context-path: /

Note that web and actuator dependencies are introduced here. By configuring management. server. port, the web endpoint of actuator is specified as port 8089, and actuator/prometheus is opened through management. endpoints. include. Endpoint/actuator/prometheus takes effect immediately after io. micrometer: micrometer-registry-prometheus dependency is introduced.


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

Reference

• HikariCP

Summarize


Related articles: