如何在我的application.properties文件中的Spring Boot应用程序中配置HikariCP?

Kev*_*n M 69 java spring spring-boot hikaricp

我正在尝试在我的Spring Boot(1.2.0.M1)应用程序中设置HikariCP,因此我可以使用它来代替Tomcat DBCP进行测试.我想在我的application.properties文件中配置连接池,就像我在使用Tomcat一样,但我无法弄清楚我应该怎么做.我发现的所有示例都显示了JavaConfig样式,或者使用单独的HikariCP属性文件.有人可以帮我弄清楚在application.properties中配置它的属性名吗?我还想从使用driverClassName方法切换到DataSourceClassName方法,因为它看起来更干净,建议使用.这在我的application.properties文件中也可以吗?

这是我对Tomcat DBCP的看法(只是一些基本的配置,没有完全刷新)

spring.datasource.validation-query=SELECT 1
spring.datasource.max-active=10
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=5
spring.datasource.test-on-borrow=true
spring.datasource.test-on-return=true
Run Code Online (Sandbox Code Playgroud)

我目前正在使用driverClassName和jdbc url来建立连接:

spring.datasource.url=jdbc:mysql://localhost:3306/myDb
spring.datasource.driverClassName=com.mysql.jdbc.Driver
Run Code Online (Sandbox Code Playgroud)

Ser*_*kin 120

@Configuration
@ConfigurationProperties(prefix = "params.datasource")
public class JpaConfig extends HikariConfig {

    @Bean
    public DataSource dataSource() throws SQLException {
        return new HikariDataSource(this);
    }

}
Run Code Online (Sandbox Code Playgroud)

application.yml

params:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    jdbcUrl: jdbc:mysql://localhost:3306/myDb
    username: login
    password: password
    maximumPoolSize: 5
Run Code Online (Sandbox Code Playgroud)

更新!自Spring Boot 1.3.0版本开始:

  1. 只需将HikariCP添加到依赖项中
  2. 配置application.yml

application.yml

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    url: jdbc:h2:mem:TEST
    driver-class-name: org.h2.Driver
    username: username
    password: password
    hikari:
      idle-timeout: 10000
Run Code Online (Sandbox Code Playgroud)

更新!自Spring Boot 2.0.0版本开始:

默认连接池已从Tomcat更改为Hikari :)

  • 以前,我们只需要通过查看数据源的文档来了解它是如何配置的,现在情况变得更糟,我们现在还需要知道在使用Spring Boot时它是如何配置的.我真的没有看到这种自动配置真正帮助我们. (3认同)
  • 这也可用于标准弹簧配置,但有人认为很重要。Hikari 通过 jdbcUrl 使用数据源的 url,但通过 url 使用 spring。{ 私人字符串网址;@Bean public DataSource dataSource() throws SQLException { return new HikariDataSource(this); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; // HikariConfig 在 jdbcUrl 属性中持有 JDBC-URL,但是 spring 提供了这个属性作为 url this.setJdbcUrl(url); } } (2认同)

use*_*765 23

您只需使用application.yml/application.properties即可.无需显式创建任何DataSourceBean

你需要排除ydemartino提到的tomcat-jdbc

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
        </exclusion>
    </exclusions>
</dependency>
Run Code Online (Sandbox Code Playgroud)

由于您不会创建DataSourcebean,因此您必须在application.yml/application.properties中使用Hikari显式指定spring.datasource.typecom.zaxxer.hikari.HikariDataSource.

spring:
    datasource:
        hikari:
            connection-test-query: SELECT 1 FROM DUAL
            minimum-idle: 1
            maximum-pool-size: 5
            pool-name: yourPoolName
            auto-commit: false
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/myDb
        username: login
        password: password
        type: com.zaxxer.hikari.HikariDataSource
Run Code Online (Sandbox Code Playgroud)

在application.yml/application.properties中,您可以配置Hikari特定参数,例如池大小等 spring.datasource.hikari.*

  • @MichaelPiefel您需要排除.`DataSourceBuilder`的javadoc说:如果Tomcat,HikariCP或Commons DBCP在类路径上,将选择其中一个(首先是Tomcat的顺序).我的测试证实了这一点. (2认同)

Raf*_*Raf 21

我遇到HikariCP了基准测试,我对它感到惊讶,我想尝试它而不是我的默认选择C3P0,令我惊讶的是,我很难做到configurations正确,因为配置因你正在使用的技术堆栈组合而有所不同.

我有启动器(使用Spring Initializer)的安装Spring Boot项目用作连接池的数据库. 我已经使用了构建工具,我想分享对我有用的内容,以便进行以下假设:JPA, Web, SecurityPostgreSQLHikariCP
Gradle

  1. Spring Boot Starter JPA(Web和安全 - 可选)
  2. Gradle也是如此
  3. PostgreSQL使用数据库运行和设置(即架构,用户,数据库)

build.gradle如果您正在使用Gradle或等效,pom.xml如果您使用maven,则需要以下内容

buildscript {
    ext {
        springBootVersion = '1.5.8.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

group = 'com'
version = '1.0'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-aop')

    // Exclude the tomcat-jdbc since it's used as default for connection pooling
    // This can also be achieved by setting the spring.datasource.type to HikariCP 
    // datasource see application.properties below
    compile('org.springframework.boot:spring-boot-starter-data-jpa') {
        exclude group: 'org.apache.tomcat', module: 'tomcat-jdbc'
    }
    compile('org.springframework.boot:spring-boot-starter-security')
    compile('org.springframework.boot:spring-boot-starter-web')
    runtime('org.postgresql:postgresql')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.springframework.security:spring-security-test')

    // Download HikariCP but, exclude hibernate-core to avoid version conflicts
    compile('com.zaxxer:HikariCP:2.5.1') {
        exclude group: 'org.hibernate', module: 'hibernate-core'
    }

    // Need this in order to get the HikariCPConnectionProvider
    compile('org.hibernate:hibernate-hikaricp:5.2.11.Final') {
        exclude group: 'com.zaxxer', module: 'HikariCP'
        exclude group: 'org.hibernate', module: 'hibernate-core'
    }
}
Run Code Online (Sandbox Code Playgroud)

上面有一堆排除build.gradle,那是因为

  1. 首先排除,指示jdbc-tomcat在下载spring-boot-starter-data-jpa依赖项时排除连接池的gradle .这可以通过设置也可以实现spring.datasource.type=com.zaxxer.hikari.HikariDataSource但是,如果我不需要它,我不想要额外的依赖
  2. 第二个排除,指示gradle hibernate-core在下载com.zaxxer依赖项时排除,因为hibernate-core已经下载了Spring Boot,我们不希望最终得到不同的版本.
  3. 第三个排除,指示gradle hibernate-core在下载hibernate-hikaricp模块时排除,以便使HikariCP org.hibernate.hikaricp.internal.HikariCPConnectionProvider用作连接提供程序而不是弃用com.zaxxer.hikari.hibernate.HikariConnectionProvider

一旦我弄明白了build.gradle什么以及要保留什么,我就准备好将datasource配置复制/粘贴到我的application.properties预期所有内容中,以便使用漂亮的颜色但不是真的,我偶然发现以下问题

  • Spring启动无法找到数据库详细信息(即url,驱动程序),因此无法设置jpa和hibernate(因为我没有将属性键值命名为right)
  • HikariCP回归 com.zaxxer.hikari.hibernate.HikariConnectionProvider
  • 指示Spring使用新的连接提供商时自动配置休眠/ JPA然后HikariCP失败,因为它一直在寻找一些后key/valueapplication.properties并抱怨dataSource, dataSourceClassName, jdbcUrl.我不得不调试HikariConfig, HikariConfigurationUtil, HikariCPConnectionProvider并发现HikariCP无法找到属性,application.properties因为它的名称不同.

无论如何,这是我不得不依赖试验和错误的地方,并确保HikariCP能够选择属性(即数据源的db详细信息,以及池属性)以及Sping Boot按预期运行,我最终得到了以下application.properties文件.

server.contextPath=/
debug=true

# Spring data source needed for Spring boot to behave
# Pre Spring Boot v2.0.0.M6 without below Spring Boot defaults to tomcat-jdbc connection pool included 
# in spring-boot-starter-jdbc and as compiled dependency under spring-boot-starter-data-jpa
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.url=jdbc:postgresql://localhost:5432/somedb
spring.datasource.username=dbuser
spring.datasource.password=dbpassword

# Hikari will use the above plus the following to setup connection pooling
spring.datasource.hikari.minimumIdle=5
spring.datasource.hikari.maximumPoolSize=20
spring.datasource.hikari.idleTimeout=30000
spring.datasource.hikari.poolName=SpringBootJPAHikariCP
spring.datasource.hikari.maxLifetime=2000000
spring.datasource.hikari.connectionTimeout=30000

# Without below HikariCP uses deprecated com.zaxxer.hikari.hibernate.HikariConnectionProvider
# Surprisingly enough below ConnectionProvider is in hibernate-hikaricp dependency and not hibernate-core
# So you need to pull that dependency but, make sure to exclude it's transitive dependencies or you will end up 
# with different versions of hibernate-core 
spring.jpa.hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider

# JPA specific configs
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.use_sql=true
spring.jpa.properties.hibernate.id.new_generator_mappings=false
spring.jpa.properties.hibernate.default_schema=dbschema
spring.jpa.properties.hibernate.search.autoregister_listeners=false
spring.jpa.properties.hibernate.bytecode.use_reflection_optimizer=false

# Enable logging to verify that HikariCP is used, the second entry is specific to HikariCP
logging.level.org.hibernate.SQL=DEBUG
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE 
Run Code Online (Sandbox Code Playgroud)

如上所示,基于以下命名模式将配置划分为类别

  • spring.datasource.x(Spring自动配置将选择这些,HikariCP也是如此)
  • spring.datasource.hikari.x(HikariCP选择这些来设置池,记下camelCase字段名称)
  • spring.jpa.hibernate.connection.provider_class(指示Spring使用新的HibernateConnectionProvider)
  • spring.jpa.properties.hibernate.x(由Spring用于自动配置JPA,记下带下划线的字段名称)

很难看到教程或帖子或某些资源,它们显示了如何使用上述属性文件以及如何命名属性.好吧,你有它.

将上面application.properties的内容build.gradle(或至少类似的)投入Spring Boot JPA项目版本(1.5.8)应该像魅力一样工作并连接到预配置的数据库(即在我的情况下,它的PostgreSQL都是HikariCP & Springspring.datasource.url哪个中找出来的数据库驱动程序使用).

我没有看到创建一个DataSourcebean 的必要性,因为Spring Boot能够通过调查application.properties和整齐来为我做一切.

HikariCP的github wiki中的文章展示了如何使用JPA设置Spring Boot,但缺乏解释和细节.

以上两个文件也可作为公共要点https://gist.github.com/rhamedy/b3cb936061cc03acdfe21358b86a5bc6


pat*_*elb 9

这将帮助任何想要使用 spring 自动配置为其应用程序配置 hikaricp 的人。对于我的项目,我使用 spring boot 2,hikaricp 作为 JDBC 连接池,mysql 作为数据库。我在其他答案中没有看到的一件事是data-source-properties它可用于设置spring.datasource.hikari.*路径中不可用的各种属性。这相当于使用HikariConfig类。要为 mysql 特定属性配置数据源和 hikaricp 连接池,我使用了 spring 自动配置注释和 application.yml 文件中的以下属性。

广场@EnableAutoConfiguration上的配置Bean文件之一。

application.yml文件看起来像这样。

spring:
  datasource:
    url: 'jdbc:mysql://127.0.0.1:3306/DATABASE?autoReconnect=true&useSSL=false'
    username: user_name
    password: password
    hikari:
      maximum-pool-size: 20
      data-source-properties:
        cachePrepStmts: true
        prepStmtCacheSize: 250
        prepStmtCacheSqlLimit: 2048
        useServerPrepStmts: true
        useLocalSessionState: true
        rewriteBatchedStatements: true
        cacheResultSetMetadata: true
        cacheServerConfiguration: true
        elideSetAutoCommits: true
        maintainTimeStats: false
Run Code Online (Sandbox Code Playgroud)


Sth*_*ita 8

根据文档进行了更改,

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html

范例:

spring:
    datasource:
        url: 'jdbc:mysql://localhost/db?useSSL=false'
        username: root
        password: pass
        driver: com.mysql.jdbc.Driver
        hikari:
            minIdle: 10
            idle-timeout: 10000
            maximumPoolSize: 30
Run Code Online (Sandbox Code Playgroud)

这些是我们可以在hikari上进行的以下配置更改,请根据您的需要进行添加/更新。

autoCommit
connectionTimeout
idleTimeout
maxLifetime
connectionTestQuery
connectionInitSql
validationTimeout
maximumPoolSize
poolName
allowPoolSuspension
readOnly
transactionIsolation
leakDetectionThreshold
Run Code Online (Sandbox Code Playgroud)


Jes*_*eta 7

这适用于我的启动应用程序,以防它有用.该类告诉您配置对象要查找的属性:

https://github.com/brettwooldridge/HikariCP/blob/2.3.x/hikaricp-common/src/main/java/com/zaxxer/hikari/AbstractHikariConfig.java

我认为通过添加datasource_whatever源配置文件中的属性键可以支持多个数据源.干杯!

@Configuration
class DataSourceConfig {

   @Value('${spring.datasource.username}')
   private String user;

   @Value('${spring.datasource.password}')
   private String password;

   @Value('${spring.datasource.url}')
   private String dataSourceUrl;

   @Value('${spring.datasource.dataSourceClassName}')
   private String dataSourceClassName;

   @Value('${spring.datasource.connectionTimeout}')
   private int connectionTimeout;

   @Value('${spring.datasource.maxLifetime}')
   private int maxLifetime;

   @Bean
   public DataSource primaryDataSource() {
      Properties dsProps = [url: dataSourceUrl, user: user, password: password]
      Properties configProps = [
            connectionTestQuery: 'select 1 from dual',
            connectionTimeout: connectionTimeout,
            dataSourceClassName: dataSourceClassName,
            dataSourceProperties: dsProps,
            maxLifetime: maxLifetime
      ]

      // A default max pool size of 10 seems reasonable for now, so no need to configure for now.
      HikariConfig hc = new HikariConfig(configProps)
      HikariDataSource ds = new HikariDataSource(hc)
      ds
   }
}
Run Code Online (Sandbox Code Playgroud)


San*_*Lee 7

将属性值放入变量时不需要冗余代码.您可以直接使用属性文件设置属性.

hikari.properties文件放在类路径中.

driverClassName=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/myDb
connectionTestQuery=SELECT 1
maximumPoolSize=20
username=...
password=...
Run Code Online (Sandbox Code Playgroud)

并创建一个像这样的数据源bean.

@Bean(destroyMethod = "close")
public DataSource dataSource() throws SQLException {
    HikariConfig config = new HikariConfig("/hikari.properties");
    HikariDataSource dataSource = new HikariDataSource(config);

    return dataSource;
}
Run Code Online (Sandbox Code Playgroud)


lev*_*ver 7

这是好消息。HikariCP 现在是 Spring Boot 2.0.0 的默认连接池。

Spring Boot 2.0.0 发行说明

Spring Boot 2.0 中默认的数据库池技术已经从 Tomcat Pool 切换到 HikariCP。我们发现 Hakari 提供了卓越的性能,与 Tomcat Pool 相比,我们的许多用户更喜欢它。


Kev*_*n M 6

所以事实证明,除了数据库连接数之外,几乎所有 HikariCP 的默认设置都对我有用。我在 application.properties 中设置了该属性:

spring.datasource.maximumPoolSize=20
Run Code Online (Sandbox Code Playgroud)

Andy Wilkinson 是正确的,据我所知,您不能将 dataSourceClassName 配置方法用于带有 Spring Boot 的 HikariCP。

  • 我已经在不同的应用程序中使用 HikariCP 一段时间了,到目前为止从未遇到任何问题。我正在使用 HikariConfig 方法,在该方法中,您将所有配置都放在一个属性文件中。SpringBoot 和 SpringCore 也可以按预期工作。我也在配置maximumPoolSize。 (2认同)

Sha*_*suf 6

你不能在@Andy Wilkinson所说的application.properties配置中使用dataSourceClassName方法.如果你想拥有dataSourceClassName,你可以使用Java Config:

@Configuration
@ComponentScan
class DataSourceConfig {

 @Value("${spring.datasource.username}")
private String user;

@Value("${spring.datasource.password}")
private String password;

@Value("${spring.datasource.url}")
private String dataSourceUrl;

@Value("${spring.datasource.dataSourceClassName}")
private String dataSourceClassName;

@Value("${spring.datasource.poolName}")
private String poolName;

@Value("${spring.datasource.connectionTimeout}")
private int connectionTimeout;

@Value("${spring.datasource.maxLifetime}")
private int maxLifetime;

@Value("${spring.datasource.maximumPoolSize}")
private int maximumPoolSize;

@Value("${spring.datasource.minimumIdle}")
private int minimumIdle;

@Value("${spring.datasource.idleTimeout}")
private int idleTimeout;

@Bean
public DataSource primaryDataSource() {
    Properties dsProps = new Properties();
    dsProps.put("url", dataSourceUrl);
    dsProps.put("user", user);
    dsProps.put("password", password);
    dsProps.put("prepStmtCacheSize",250);
    dsProps.put("prepStmtCacheSqlLimit",2048);
    dsProps.put("cachePrepStmts",Boolean.TRUE);
    dsProps.put("useServerPrepStmts",Boolean.TRUE);

    Properties configProps = new Properties();
       configProps.put("dataSourceClassName", dataSourceClassName);
       configProps.put("poolName",poolName);
       configProps.put("maximumPoolSize",maximumPoolSize);
       configProps.put("minimumIdle",minimumIdle);
       configProps.put("minimumIdle",minimumIdle);
       configProps.put("connectionTimeout", connectionTimeout);
       configProps.put("idleTimeout", idleTimeout);
       configProps.put("dataSourceProperties", dsProps);

   HikariConfig hc = new HikariConfig(configProps);
   HikariDataSource ds = new HikariDataSource(hc);
   return ds;
   }
  } 
Run Code Online (Sandbox Code Playgroud)

之所以你不能使用dataSourceClassName,因为它会抛出异常

Caused by: java.lang.IllegalStateException: both driverClassName and dataSourceClassName are specified, one or the other should be used.
Run Code Online (Sandbox Code Playgroud)

这意味着spring boot从spring.datasource.url属性推断Driver,同时设置dataSourceClassName会创建此异常.为了使其正确,您的application.properties对于HikariCP数据源看起来应该是这样的:

# hikariCP 
  spring.jpa.databasePlatform=org.hibernate.dialect.MySQLDialect
  spring.datasource.url=jdbc:mysql://localhost:3306/exampledb
  spring.datasource.username=root
  spring.datasource.password=
  spring.datasource.poolName=SpringBootHikariCP
  spring.datasource.maximumPoolSize=5
  spring.datasource.minimumIdle=3
  spring.datasource.maxLifetime=2000000
  spring.datasource.connectionTimeout=30000
  spring.datasource.idleTimeout=30000
  spring.datasource.pool-prepared-statements=true
  spring.datasource.max-open-prepared-statements=250
Run Code Online (Sandbox Code Playgroud)

注意:请检查类路径中是否有任何tomcat-jdbc.jar或commons-dbcp.jar是否通过传递依赖添加了大部分时间.如果这些存在于类路径中,则Spring Boot将使用默认连接池(即tomcat)配置数据源.如果类路径中没有其他提供程序,HikariCP将仅用于创建数据源.从tomcat - >到HikariCP - >到Commons DBCP有一个回退序列.


yde*_*ino 6

您可以使用dataSourceClassName方法,这是MySQL的一个示例.(经过春季靴子1.3和1.4测试)

首先,您需要从类路径中排除tomcat-jdbc,因为它将被选中以支持hikaricp.

的pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

application.properties

spring.datasource.dataSourceClassName=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
spring.datasource.dataSourceProperties.serverName=localhost
spring.datasource.dataSourceProperties.portNumber=3311
spring.datasource.dataSourceProperties.databaseName=mydb
spring.datasource.username=root
spring.datasource.password=root
Run Code Online (Sandbox Code Playgroud)

然后添加

@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}
Run Code Online (Sandbox Code Playgroud)

我在这里创建了一个测试项目:https://github.com/ydemartino/spring-boot-hikaricp


Wat*_*ter 5

我正在使用Spring Boot 2.0.4.RELEASE。Hikari是默认的连接池,.hikari不再需要。

application.properties

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.jdbcUrl=jdbc:mysql://localhost:3306/myDB...
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.poolname=myPool
Run Code Online (Sandbox Code Playgroud)

application.yml

spring:
    datasource:
        driverClassName: com.mysql.jdbc.Driver
        jdbcUrl: jdbc:mysql://localhost:3306/myDB...
        username: xxx
        password: xxx
        poolName: myPool
Run Code Online (Sandbox Code Playgroud)

并且configuration不需要扩展HikariConfig,并且DataSourceBuilder可以像以前一样使用。

@Configuration
public class DataSourceConfiguration {

    @Bean(name="myDataSource")
    @ConfigurationProperties("spring.datasource")
    public DataSource myDataSource() {
        return DataSourceBuilder.create().build();
    }
}
Run Code Online (Sandbox Code Playgroud)