Datasource

许多使用数据的项目都需要连接到关系数据库。

获取数据库连接通常方式是使用数据源并配置 JDBC 驱动程序。 但你也可能喜欢使用反应式驱动程序以反应式连接到数据库。

Quarkus 两种方式都支持:

  • 对于 JDBC,首选的数据源和连接池实现是 Agroal

  • 对于反应式,我们使用 Vert.x reactive 驱动程序。

两者都是通过统一灵活的配置进行配置。

Agroal 是一个现代的轻量连接池实现,为高性能和可扩展性设计, 便于与 Quarkus 其他组件集成,例如安全、事务管理组件、健康检测等。

本指南将说明如何:

  • 配置一个或多个数据源

  • 如何在代码中获取这些数据源的引用

  • 哪些资源库配置属性可调整

本指南主要涉及数据源配置。 如果你想了解关于如何消费和使用反应式数据源的详细信息, 请参阅 Reactive SQL clients 指南

摘要

这是对数据源配置的快速介绍。 如果你想要更好地了解所有这些工作的情况,本指南在以下各段有更多的信息。

JDBC 数据源

添加 agroal 扩展及一个 jdbc-derby, jdbc-h2, jdbc-mariadb, jdbc-mssql, jdbc-mysqljdbc-postgresql

然后配置您的数据源:

quarkus.datasource.db-kind=postgresql
quarkus.datasource.username=<your username>
quarkus.datasource.password=<your password>

quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/hibernate_orm_test
quarkus.datasource.jdbc.min-size=4
quarkus.datasource.jdbc.max-size=16

反应式数据源

添加 reactive-pg-clientreactive-mysql-client 扩展。

然后配置您的反应式数据源:

quarkus.datasource.db-kind=postgresql
quarkus.datasource.username=<your username>
quarkus.datasource.password=<your password>

quarkus.datasource.reactive.url=postgresql:///your_database
quarkus.datasource.reactive.max-size=20

默认数据源

数据源可以是JDBC数据源,也可以是反应数据源,也可以是两者混用。 这完全取决于你如何配置它以及你添加到你的项目的扩展。

要定义数据源,首先如下所示:

quarkus.datasource.db-kind=h2

数据库类型定义了您要连接的数据库类型。

我们目前包含这些内置数据库类型:

  • Derby: derby

  • H2: h2

  • MariaDB: mariadb

  • Microsoft SQL Server: mssql

  • MySQL: mysql

  • PostgreSQL: postgresql, pgsql or pg

指定 Quarkus 数据库类型以便于配置。 使用一个 JDBC 驱动扩展并设置配置中的类型, Quarkus 自动解决了 JDBC 驱动程序, 因此您不需要自己进行配置。 如果你想使用内建数据库之外的数据库,请使用 "other" 并明确定义 JDBC 驱动程序。

您可以在 JVM 模式的 Quarkus 应用程序中使用任何 JDBC 驱动程序(见Using other databases)。 在编译成 native 时可能不会奏效。

如果你想做成 native 可执行文件, 我们建议你使用现有的 JDBC Quarkus 扩展(或为贡献一个你的驱动程序)。

定义一些凭据才能访问您的数据库。

这是通过配置以下属性完成的:

quarkus.datasource.username=<your username>
quarkus.datasource.password=<your password>

您也可以为数据源通过 Vault using a credential provider 获取密码。

一旦您定义了数据库类型和凭据,您就可以配置一个 JDBC 数据源,一个被动数据源,或两者兼而有之。

JDBC 数据源

JDBC 是最常见的数据库连接模式。 使用Hibernate ORM时,您通常需要一个 JDBC 数据源。

安装 Maven 依赖关系

首先,您需要将 quarkus-agroal 依赖添加到您的项目。

您可以使用简单的 Maven 命令添加它:

./mvnw quarkus:add-extension -Dextensions="agroal"

Agroal 是 Hibernate ORM 扩展的隐式依赖,所以如果您正在使用 Hibernate ORM 您不需要明确添加 Agroal 扩展依赖项。

您还需要为您的关系数据库驱动程序选择并添加Quarkus扩展。

Quarkus 提供驱动扩展:

  • Derby - jdbc-derby

  • H2 - jdbc-h2

  • MariaDB - jdbc-mariadb

  • Microsoft SQL Server - jdbc-mssql

  • MySQL - jdbc-mysql

  • PostgreSQL - jdbc-postgresql

如果您想要使用其它数据库请参阅使用没有内置扩展或具有其他驱动程序的数据库 指定 JDBC 驱动程序。

H2 和 Derby 数据库通常可以配置为“嵌入模式”运行; 扩展不支持将嵌入数据库引擎编译成native images。

查阅 Testing with in-memory databases (下面) 获取关于集成测试的建议。

一般您可以使用 add-extension 安装扩展。

要安装 PostgreSQL 驱动依赖关系,请运行以下命令:

./mvnw quarkus:add-extension -Dextensions="jdbc-postgresql"

配置 JDBC 连接

配置您的 JDBC 连接很容易,唯一必须的属性是 JDBC URL。

quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/hibernate_orm_test

注意属性名称中的 jdbc 前缀。 所有与 JDBC 特定的配置属性都有此前缀。

关于JDBC URL 格式的更多信息,请参阅 JDBC url reference section.

当使用内置数据源类型之一时,对应 JDBC 驱动为:

Table 1. 数据库类型对应的 JDBC 驱动程序
数据库类型(kind) JDBC 驱动 XA 驱动

derby

org.apache.derby.jdbc.ClientDriver

org.apache.derby.jdbc.ClientXADataSource

h2

org.h2.Driver

org.h2.jdbcx.JdbcDataSource

mariadb

org.mariadb.jdbc.Driver

org.mariadb.jdbc.MySQLDataSource

mssql

com.microsoft.sqlserver.jdbc.SQLServerDriver

com.microsoft.sqlserver.jdbc.SQLServerXADataSource

mysql

com.mysql.cj.jdbc.Driver

com.mysql.cj.jdbc.MysqlXADataSource

postgresql

org.postgresql.Driver

org.postgresql.xa.PGXADataSource

如前所述,一般自动使用的驱动都是适合您的, 您不需要配置驱动程序。

使用没有内置扩展或具有其他驱动程序的数据库

如果您需要使用指定的驱动程序(例如使用 OpenTracking 驱动程序) 或如果您想要使用一个 Quarkus 没有内置的 JDBC 驱动程序扩展的数据库。

没有扩展,驱动程序将在 JVM 模式下运行的 Quarkus 应用程序中正常工作。 在编译成 native 时可能不会奏效。 如果你想做成 native 可执行文件, 我们建议你使用现有的 JDBC Quarkus 扩展(或为贡献一个你的驱动程序)。

以下是您如何使用 OpenTracking 驱动程序:

quarkus.datasource.jdbc.driver=io.opentracing.contrib.jdbc.TracingDriver

以下是您如何定义对没有内置支持的数据库的访问权(在 JVM 模式下):

quarkus.datasource.db-kind=other
quarkus.datasource.jdbc.driver=oracle.jdbc.driver.OracleDriver
quarkus.datasource.jdbc.url=jdbc:oracle:thin:@192.168.1.12:1521/ORCL_SVC
quarkus.datasource.username=scott
quarkus.datasource.password=tiger

更多配置

您可以配置更多的东西,例如连接池的大小。

关于 JDBC 配置的所有详细信息,请参阅JDBC configuration reference

使用数据源

如果您正在使用 Hibernate ORM,数据源将被自动使用。

如果不论出于何种原因,需要在代码中访问数据源,可以以下列方式获得该数据源:

@Inject
AgroalDataSource defaultDataSource;

在上述示例中,类型是 AgroalDataSource ,它是 javax.sql.DataSource 的子类型。 因此,你也可以使用 'javax.sql.DataSource' 作为注入的类型。

反应式数据源

如果您喜欢使用反应式数据源,Quarkus 提供 MySQL/MariaDB 和 PostgreSQL 反应式客户端。

安装 Maven 依赖关系

取决于您想要使用 MySQL/MariaDB 或 PostgreSQL,您需要添加 quarkus-reactive-pg-clientquarkus-reactive-mysql-client 扩展。

已安装的扩展必须与数据源配置中 quarkus.datasource.db-kind 定义一致。

配置 JDBC 数据源

一旦驱动程序就位,您只需要配置连接 URL。

可选但高度推荐,应该为连接池定义适当的大小。

quarkus.datasource.reactive.url=postgresql:///your_database
quarkus.datasource.reactive.max-size=20

两者都是

默认情况下,如果您同时包含一个 JDBC 扩展 (+ Agroal) 和反应式数据源扩展, 两者都将被创建。

如果您想要明确禁用JDBC 数据源,请使用:

quarkus.datasource.jdbc=false

如果您想要明确禁用反应式数据源,请使用:

quarkus.datasource.reactive=false

上面的配置不是必须的,因为 JDBC 驱动程序或反应式数据源扩展一般情况不会同时出现。

多个数据源

配置多个数据源

现在,多个数据源只支持 JDBC 和 Agroal 扩展。 所以目前无法创建多个反应式数据源。

目前,Hibernate ORM 只支持一个使用默认数据源的 persistence unit 单位。 如果你想要使用多个数据源,你需要直接操作它们。

未来版本 Quarkus 计划提供多个persistence unit 支持。

定义多个数据源与定义单个数据源完全相同,但有一个重要的变化: 您定义了一个名字。

在下面的示例中,您有3个不同的数据源:

  • 一个默认的

  • 一个名为 users 的数据源,

  • 一个数据源,名为 inventory

每个配置都有自己的配置。

quarkus.datasource.db-kind=h2
quarkus.datasource.username=username-default
quarkus.datasource.jdbc.url=jdbc:h2:tcp://localhost/mem:default
quarkus.datasource.jdbc.min-size=3
quarkus.datasource.jdbc.max-size=13

quarkus.datasource.users.db-kind=h2
quarkus.datasource.users.username=username1
quarkus.datasource.users.jdbc.url=jdbc:h2:tcp://localhost/mem:users
quarkus.datasource.users.jdbc.min-size=1
quarkus.datasource.users.jdbc.max-size=11

quarkus.datasource.inventory.db-kind=h2
quarkus.datasource.inventory.username=username2
quarkus.datasource.inventory.jdbc.url=jdbc:h2:tcp://localhost/mem:inventory
quarkus.datasource.inventory.jdbc.min-size=2
quarkus.datasource.inventory.jdbc.max-size=12

请注意 key 中有一个额外地方。 语法如下: quarkus.datasource.[optional name.][datasource property].

命名数据源注入

当使用多个数据源时,每一个 DataSource 都有 io.quarkus.agroal.DataSource 注解,其值为数据源名称。 使用上述属性配置三个不同的数据源,您也可以按以下方式注入每个源:

@Inject
AgroalDataSource defaultDataSource;

@Inject
@DataSource("users")
AgroalDataSource usersDataSource;

@Inject
@DataSource("inventory")
AgroalDataSource inventoryDataSource;

数据源健康检查

如果您使用 quarkus-smallrye-health 扩展,quarkus-agroal 将自动添加准备状态健康检查 来验证数据源。

所以当您访问应用程序的 /health/ready 接口时,您将获得关于数据源状态验证信息。 如果您有多个数据源,将检查所有数据源,一旦某个数据源验证失败,状态将为 DOWN

这种行为可以通过属性 quarkus.datasource.health.enabled 禁用。

数据源指标

如果你正在使用 quarkus-smallrye-methrics 扩展,quarkus-agroal 可以在 /metrics 接口上暴露某些数据源指标。 这可以通过设置属性 quarkus.datasource.metrics.enabled 为 true 来打开.

要使暴露的计量器含有任何实际值,就必须通过 Agroal 机制内部启用计量采集。 默认, 如果 quarkus-smallye-mallrye-metrics 存在并且启用了 Agroal 扩展的计量,那么所有数据源的计量采集机制都会被打开了。 如果您想要禁用特定数据源的计量, 可以设置 quarkus.datasource.jdbc.enable-metricsfalse (或命名数据源的 quarkus.datasource.<datasource name>.jdbc.enable-metrics ). 这将禁止收集这些计量也禁止在 /metrics 接口曝光。 因为如果禁止采集的再揭露这些数据是没有意义的。

反之,将 quarkus.datasource.jdbc.enable-metrics 设置为 true (或命名数据源 quarkus.datasource.<datasource name>.jdbc.enable-metrics )显然可以用来进行计量的收集,即使没有使用 的 quarkus-smallye-mallye-metrics 扩展。 如果您需要编程访问收集到的计量,这可能是有用的。 他们可以在一个注入的 AgroalDataSource 实例上调用 dataSource.getMetrics() 后使用。 如果数据源禁用计量采集 则所有值都为零。

Narayana 事务管理器集成

如果 Narayana JTA 扩展也可用,集成是自动的。

您可以通过设置 transactions 配置属性来覆盖此设置 - 查看下面的 Configuration Reference

用内存数据库测试

一些数据库,如 H2 和 Derby ,通常被用于“嵌入模式”,作为进行快速集成测试的设施。

我们的建议是使用生产将使用的真正数据库; 容器技术使这个问题变得足够简单,你不再有任何借口。 然而,有时 也有很好的理由想要能够使用JVM驱动的数据库进行快速集成测试。 这也是可能的。

必须记住,在配置H2(或Derby) 使用嵌入引擎时, 这将以JVM模式正常工作,但这种应用程序不会编译成 native 镜像, 因为 Quarkus 扩展仅覆盖使JDBC 客户端代码与 native 编译步骤兼容:目前尚未实现将整个数据库引擎嵌入到native 镜像中。

如果你计划仅在 JVM 中运行这种集成测试,它当然会像往常一样工作。

如果你想要在JVM和/或本机图像中运行这种集成测试的能力, 我们有一些你很酷的助手:只需添加 @QuarkusTestResource(H2DatabaseTestResource.class)@QuarkusTestResource(DerbyDatabaseTestResource.class) 到你的集成测试类,这将确保测试套件在独立进程启动(和停止)嵌入的数据库来运行您的测试。

这些额外的帮助类在 Maven 包 io.quarkus:quarkus-test-h2io.quarkus:quarkus-test-derby, 分别对应 H2 和 Derby.

下列是一个 H2 的例子:

package my.app.integrationtests.db;

import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.h2.H2DatabaseTestResource;

@QuarkusTestResource(H2DatabaseTestResource.class)
public class TestResources {
}

这将允许您测试应用程序,即使它被编译成 native 镜像, 数据库将一如既往地在 JVM 中运行。

使用以下方式连接它:

quarkus.datasource.url=jdbc:h2:tcp://localhost/mem:test
quarkus.datasource.driver=org.h2.Driver

通用数据源配置引用

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

The kind of database we will connect to (e.g. h2, postgresql…​).

string

Whether or not an health check is published in case the smallrye-health extension is present. This is a global setting and is not specific to a datasource.

boolean

true

Whether or not datasource metrics are published in case the smallrye-metrics extension is present. This is a global setting and is not specific to a datasource. NOTE: This is different from the "jdbc.enable-metrics" property that needs to be set on the JDBC datasource level to enable collection of metrics for that datasource.

boolean

false

The datasource username

string

The datasource password

string

The credentials provider name

string

The credentials provider type. It is the @Named value of the credentials provider bean. It is used to discriminate if multiple CredentialsProvider beans are available. For Vault it is: vault-credentials-provider. Not necessary if there is only one credentials provider available.

string

int

20

Additional named datasources

Type

Default

The kind of database we will connect to (e.g. h2, postgresql…​).

string

string

string

string

The credentials provider type. It is the @Named value of the credentials provider bean. It is used to discriminate if multiple CredentialsProvider beans are available. For Vault it is: vault-credentials-provider. Not necessary if there is only one credentials provider available.

string

int

20

JDBC 配置参考

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

If we create a JDBC datasource for this datasource.

boolean

true

The datasource driver class name

string

Whether we want to use regular JDBC transactions, XA, or disable all transactional capabilities. When enabling XA you will need a driver implementing javax.sql.XADataSource.

enabled, xa, disabled

enabled

Enable datasource metrics collection. If unspecified, collecting metrics will be enabled by default if the smallrye-metrics extension is active.

boolean

The datasource URL

string

The initial size of the pool. Usually you will want to set the initial size to match at least the minimal size, but this is not enforced so to allow for architectures which prefer a lazy initialization of the connections on boot, while being able to sustain a minimal pool size after boot.

int

The datasource pool minimum size

int

0

The datasource pool maximum size

int

20

The interval at which we validate idle connections in the background. Set to 0 to disable background validation.

Duration

2M

The timeout before cancelling the acquisition of a new connection

Duration

5

The interval at which we check for connection leaks.

Duration

The interval at which we try to remove idle connections.

Duration

5M

The max lifetime of a connection.

Duration

The transaction isolation level.

undefined, none, read-uncommitted, read-committed, repeatable-read, serializable

When enabled Agroal will be able to produce a warning when a connection is returned to the pool without the application having closed all open statements. This is unrelated with tracking of open connections. Disable for peak performance, but only when there’s high confidence that no leaks are happening.

boolean

true

Query executed when first using a connection.

string

Query executed to validate a connection.

string

Additional named datasources

Type

Default

If we create a JDBC datasource for this datasource.

boolean

true

The datasource driver class name

string

Whether we want to use regular JDBC transactions, XA, or disable all transactional capabilities. When enabling XA you will need a driver implementing javax.sql.XADataSource.

enabled, xa, disabled

enabled

Enable datasource metrics collection. If unspecified, collecting metrics will be enabled by default if the smallrye-metrics extension is active.

boolean

string

The initial size of the pool. Usually you will want to set the initial size to match at least the minimal size, but this is not enforced so to allow for architectures which prefer a lazy initialization of the connections on boot, while being able to sustain a minimal pool size after boot.

int

The datasource pool minimum size

int

0

The datasource pool maximum size

int

20

The interval at which we validate idle connections in the background. Set to 0 to disable background validation.

Duration

2M

The timeout before cancelling the acquisition of a new connection

Duration

5

The interval at which we check for connection leaks.

Duration

The interval at which we try to remove idle connections.

Duration

5M

The max lifetime of a connection.

Duration

undefined, none, read-uncommitted, read-committed, repeatable-read, serializable

When enabled Agroal will be able to produce a warning when a connection is returned to the pool without the application having closed all open statements. This is unrelated with tracking of open connections. Disable for peak performance, but only when there’s high confidence that no leaks are happening.

boolean

true

Query executed when first using a connection.

string

Query executed to validate a connection.

string

About the Duration format

The format for durations uses the standard java.time.Duration format. You can learn more about it in the Duration#parse() javadoc.

You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, PT is implicitly prepended to the value to obtain a standard java.time.Duration format.

JDBC URL 引用

每个支持的数据库包含不同的 JDBC URL 配置选项。 每一种都超出了本文件的范围, 但以下部分提供了每种数据库的 URL 概览和官方文档的链接。

H2

jdbc:h2:{ {.|mem:}[name] | [file:]fileName | {tcp|ssl}:[//]server[:port][,server2[:port]]/name }[;key=value…​]

示例

jdbc:h2:tcp://localhost/~/test, jdbc:h2:mem:myDB

H2是一个嵌入的数据库。 它可以作为服务器运行,基于文件或者完全存活在内存中。 所有这些选项都如上文所示。 您可以在 官方文档 找到更多信息。

PostgreSQL

PostgreSQL 只能作为服务器运行,下面其它数据库也是如此。 因此,您必须指定连接详情,或使用默认值。

jdbc:postgresql:[//][host][:port][/database][?key=value…​]

示例

jdbc:postgresql://localhost/test

不同部分的默认值如下:

host

localhost

port

5432

database

与用户名相同

官方文件 更详细地列出可选参数。

MariaDB

jdbc:mariadb:[replication:|failover:|sequential:|aurora:]//<hostDescription>[,<hostDescription>…​]/[database][?<key1>=<value1>[&<key2>=<value2>]] hostDescription:: <host>[:<portnumber>] or address=(host=<host>)[(port=<portnumber>)][(type=(master|slave))]

示例

jdbc:mariadb://localhost:3306/test

您可以在 官方文档 中找到更多关于此功能和其他功能的信息。

MySQL

jdbc:mysql:[replication:|failover:|sequential:|aurora:]//<hostDescription>[,<hostDescription>…​]/[database][?<key1>=<value1>[&<key2>=<value2>]] hostDescription:: <host>[:<portnumber>] or address=(host=<host>)[(port=<portnumber>)][(type=(master|slave))]

示例

jdbc:mysql://localhost:3306/test

您可以在 官方文档 中找到更多有关此功能和其他功能的信息。

Microsoft SQL Server

Microsoft SQL Server 采用以下形式的连接 URL:

jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]

示例

jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks

Microsoft SQL Server JDBC 驱动程序与其他驱动程序基本相同。 更多详情参阅 官方文档

Derby

jdbc:derby:[//serverName[:portNumber]/][memory:]databaseName[;property=value[;property=value]]

示例

jdbc:derby://localhost:1527/myDB, jdbc:derby:memory:myDB;create=true

Derby 是一个嵌入的数据库。 它可以作为服务器运行,基于文件或者完全存活在内存中。 所有这些选项都如上文所示。 您可以在 官方文档 查看更多信息。

反应式数据源配置参考

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

If we create a Reactive datasource for this datasource.

boolean

true

The datasource URL.

string

The datasource pool maximum size.

int

反应式 MariaDB/MySQL 特定配置

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

Whether prepared statements should be cached on the client side.

boolean

string

Collation for connections.

string

反应式 PostgreSQL 特定配置

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

Whether prepared statements should be cached on the client side.

boolean

The maximum number of inflight database commands that can be pipelined.

int

quarkus.pro 是基于 quarkus.io 的非官方中文翻译站 ,最后更新 2020/04 。
沪ICP备19006215号-8
QQ交流群:1055930959
微信群: