Configure data sources in {project-name}
使用统一的配置模型为 Java 数据库连接(JDBC)和反应式驱动程序定义数据源。
Use a unified configuration model to define data sources for Java Database Connectivity (JDBC) and Reactive drivers.
应用程序使用数据源来访问关系数据库。Quarkus 提供了一个统一的配置模型来为 Java 数据库连接(JDBC)和反应式数据库驱动程序定义数据源。
Applications use datasources to access relational databases. Quarkus provides a unified configuration model to define datasources for Java Database Connectivity (JDBC) and Reactive database drivers.
Quarkus 使用 Agroal和 Vert.x为 JDBC 和反应式驱动程序提供高性能、可扩展的数据源连接池。quarkus-jdbc-
and `quarkus-reactive--client`扩展提供构建时优化,并将配置的数据源与 Quarkus 特性集成,如安全性、运行状况检查和指标。
Quarkus uses Agroal and Vert.x to provide high-performance, scalable data source connection pooling for JDBC and reactive drivers.
The quarkus-jdbc-
and quarkus-reactive--client
extensions provide build time optimizations and integrate configured data sources with Quarkus features like security, health checks, and metrics.
有关使用反应式数据源的更多信息,请参阅 Quarkus Reactive SQL clients指南。
For more information about consuming and using a reactive datasource, see the Quarkus Reactive SQL clients guide.
此外,请参阅 Quarkus Hibernate ORM指南以了解有关使用 JDBC 数据源的信息。
Additionally, refer to the Quarkus Hibernate ORM guide for information on consuming and using a JDBC datasource.
Get started with configuring datasources
in Quarkus
对于熟悉基本知识的用户,本部分提供了快速设置数据源的概述和代码示例。
For users familiar with the fundamentals, this section provides an overview and code samples to set up data sources quickly.
有关示例的高级配置,请参阅 References。
For more advanced configuration with examples, see References.
Zero-config setup in development mode
Quarkus 通过提供开发服务功能来简化数据库配置,从而实现在开发(dev)模式下进行测试或运行的零配置数据库设置。在 dev 模式下,建议的方法是使用 DevServices 并让 Quarkus 为您处理数据库,而在生产模式下,您提供指向 Quarkus 外部管理的数据库的显式数据库配置详细信息。
Quarkus simplifies database configuration by offering the Dev Services feature, enabling zero-config database setup for testing or running in development (dev) mode. In dev mode, the suggested approach is to use DevServices and let Quarkus handle the database for you, whereas for production mode, you provide explicit database configuration details pointing to a database managed outside of Quarkus.
要使用 Dev Services,请为所需的数据库类型将适当的驱动程序扩展(如 jdbc-postgresql
)添加到 `pom.xml`文件中。在 dev 模式下,如果您未提供任何显式数据库连接详细信息,则 Quarkus 将自动处理数据库设置并提供应用程序与数据库之间的连接。
To use Dev Services, add the appropriate driver extension, such as jdbc-postgresql
, for your desired database type to the pom.xml
file.
In dev mode, if you do not provide any explicit database connection details, Quarkus automatically handles the database setup and provides the wiring between the application and the database.
如果您提供用户凭据,则将配置基础数据库以使用它们。如果您想使用外部工具连接到数据库,这非常有用。
If you provide user credentials, the underlying database will be configured to use them. This is useful if you want to connect to the database with an external tool.
要使用此特性,请确保已安装与数据库类型相关的 Docker 或 Podman 容器运行时。某些数据库(如 H2)以内存模式运行,不需要容器运行时。
To use this feature, ensure a Docker or Podman container runtime is installed, depending on the database type. Certain databases, such as H2, operate in in-memory mode and do not require a container runtime.
使用 `%prod.`为生产模式的实际连接详细信息加上前缀,以确保它们不会在 dev 模式下应用。有关详细信息,请参阅“配置参考”指南的 Profiles部分。 |
Prefix the actual connection details for prod mode with |
有关 Dev 服务的更多信息,请参阅 Dev Services overview。
For more information about Dev Services, see Dev Services overview.
有关更多详情和可选配置,请参阅 Dev Services for databases。
For more details and optional configurations, see Dev Services for databases.
Configure a JDBC datasource
-
Add the correct JDBC extension for the database of your choice.
-
quarkus-jdbc-db2
-
quarkus-jdbc-derby
-
quarkus-jdbc-h2
-
quarkus-jdbc-mariadb
-
quarkus-jdbc-mssql
-
quarkus-jdbc-mysql
-
quarkus-jdbc-oracle
-
quarkus-jdbc-postgresql
-
-
Configure your JDBC datasource:[source, properties]
quarkus.datasource.db-kind=postgresql 1 quarkus.datasource.username=<your username> quarkus.datasource.password=<your password> quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/hibernate_orm_test quarkus.datasource.jdbc.max-size=16
1 | This configuration value is only required if there is more than one database extension on the classpath. |
如果只有一个可行的扩展可用,Quarkus 假定这是正确的扩展。当您将驱动程序添加到测试作用域时,Quarkus 会在测试中自动包含指定的驱动程序。
If only one viable extension is available, Quarkus assumes this is the correct one. When you add a driver to the test scope, Quarkus automatically includes the specified driver in testing.
JDBC connection pool size adjustment
为了在负载高峰期间防止数据库过载,请适当调整连接池大小以限制数据库负载。最佳连接池大小取决于诸多因素,例如并行应用程序用户的数量或工作负荷的性质。
To protect your database from overloading during load peaks, size the pool adequately to throttle the database load. The optimal pool size depends on many factors, such as the number of parallel application users or the nature of the workload.
请注意,设置过小的连接池大小可能会导致一些请求在等待连接时超时。
Be aware that setting the pool size too low might cause some requests to time out while waiting for a connection.
有关连接池大小调整属性的更多信息,请参阅 JDBC configuration reference 部分。
For more information about pool size adjustment properties, see the JDBC configuration reference section.
Configure a reactive datasource
-
Add the correct reactive extension for the database of your choice.
-
quarkus-reactive-db2-client
-
quarkus-reactive-mssql-client
-
quarkus-reactive-mysql-client
-
quarkus-reactive-oracle-client
-
quarkus-reactive-pg-client
-
-
Configure your reactive datasource:[source, properties]
quarkus.datasource.db-kind=postgresql 1 quarkus.datasource.username=<your username> quarkus.datasource.password=<your password> quarkus.datasource.reactive.url=postgresql:///your_database quarkus.datasource.reactive.max-size=20
1 | This configuration value is only required if there is more than one Reactive driver extension on the classpath. |
Configure datasources
以下部分介绍了单数据源或多数据源的配置。为简单起见,我们将引用单数据源作为默认(未命名)数据源。
The following section describes the configuration for single or multiple datasources. For simplicity, we will reference a single datasource as the default (unnamed) datasource.
Configure a single datasource
数据源可以是 JDBC 数据源、反应性数据源,或两者兼有。这取决于配置和项目扩展的选择。
A datasource can be either a JDBC datasource, reactive, or both. This depends on the configuration and the selection of project extensions.
-
Define a datasource with the following configuration property, where
db-kind
defines which database platform to connect to, for example,h2
:[source, properties]
quarkus.datasource.db-kind=h2
Quarkus 从指定的值 db-kind
数据库平台属性中推导出它需要使用的 JDBC 驱动程序类。
Quarkus deduces the JDBC driver class it needs to use from the specified value of the db-kind
database platform attribute.
仅当您的应用程序依赖于多个数据库驱动程序时,才需要此步骤。如果应用程序使用单个驱动程序,此驱动程序将自动检测到。 |
This step is required only if your application depends on multiple database drivers. If the application operates with a single driver, this driver is detected automatically. |
Quarkus 当前包含以下内置数据库类型:
Quarkus currently includes the following built-in database kinds:
-
DB2:
db2
-
Derby:
derby
-
H2:
h2
-
MariaDB:
mariadb
-
Microsoft SQL Server:
mssql
-
MySQL:
mysql
-
Oracle:
oracle
-
PostgreSQL:
postgresql
,pgsql
orpg
-
To use a database kind that is not built-in, use
other
and define the JDBC driver explicitly
您可以在 Quarkus 应用程序中使用 Using other databases 中描述的任何 JDBC 驱动程序(在 JVM 模式下)。不过,将您的应用程序编译为原生可执行文件时,使用非内置数据库类型不太可能起作用。
You can use any JDBC driver in a Quarkus app in JVM mode as described in other-databases. However, using a non-built-in database kind is unlikely to work when compiling your application to a native executable.
对于本地可执行版本,建议使用可用的 JDBC Quarkus 扩展,或者为特定的驱动器贡献一个自定义扩展。
For native executable builds, it is recommended to either use the available JDBC Quarkus extensions or contribute a custom extension for your specific driver.
-
Configure the following properties to define credentials:[source, properties]
quarkus.datasource.username=<your username> quarkus.datasource.password=<your password>
您还可以通过 using a credential provider 从 Vault 为数据源检索密码。
You can also retrieve the password from Vault by using a credential provider for your datasource.
到目前为止,无论您使用的是 JDBC 驱动程序还是响应式驱动程序,该配置都是相同的。在您定义了数据库类型和凭据之后,其余部分取决于您使用的驱动程序类型。可以同时使用 JDBC 和响应式驱动程序。
Until now, the configuration has been the same regardless of whether you are using a JDBC or a reactive driver. When you have defined the database kind and the credentials, the rest depends on what type of driver you are using. It is possible to use JDBC and a reactive driver simultaneously.
JDBC datasource
JDBC 是最常见的数据库连接模式,通常在与非响应式 Hibernate ORM 结合使用时需要。
JDBC is the most common database connection pattern, typically needed when used in combination with non-reactive Hibernate ORM.
-
To use a JDBC datasource, start with adding the necessary dependencies:[style="loweralpha"]
-
For use with a built-in JDBC driver, choose and add the Quarkus extension for your relational database driver from the list below:
-
Derby -
quarkus-jdbc-derby
-
H2 -
quarkus-jdbc-h2
-
-
H2 和 Derby 数据库可以配置为在“嵌入式模式”下运行;但是,Derby 扩展不支持将嵌入式数据库引擎编译成本地可执行文件。
H2 and Derby databases can be configured to run in "embedded mode"; however, the Derby extension does not support compiling the embedded database engine into native executables.
阅读 Testing with in-memory databases 以获取有关集成测试的建议。
Read in-memory-databases for suggestions regarding integration testing.
-
DB2 -
quarkus-jdbc-db2
-
MariaDB -
quarkus-jdbc-mariadb
-
Microsoft SQL Server -
quarkus-jdbc-mssql
-
MySQL -
quarkus-jdbc-mysql
-
Oracle -
quarkus-jdbc-oracle
-
PostgreSQL -
quarkus-jdbc-postgresql
-
Other JDBC extensions, such as SQLite and its documentation, can be found in the Quarkiverse.[.iokays-translated-f71ac0399bd972d9a932ff4e88680c05] 例如,要添加 PostgreSQL 驱动程序依赖关系:
For example, to add the PostgreSQL driver dependency:
./mvnw quarkus:add-extension -Dextensions="jdbc-postgresql"
使用内置 JDBC 驱动程序扩展会自动包括 Agroal 扩展,该扩展是适用于自定义和内置 JDBC 驱动程序的 JDBC 连接池实现。但是,对于自定义驱动器,需要显式添加 Agroal。 Using a built-in JDBC driver extension automatically includes the Agroal extension, which is the JDBC connection pool implementation applicable for custom and built-in JDBC drivers. However, for custom drivers, Agroal needs to be added explicitly. |
-
For use with a custom JDBC driver, add the
quarkus-agroal
dependency to your project alongside the extension for your relational database driver:[source, bash]
./mvnw quarkus:add-extension -Dextensions="agroal"
要对其他数据库使用 JDBC 驱动程序,请 use a database with no built-in extension or with a different driver。
To use a JDBC driver for another database, other-databases.
-
Configure the JDBC connection by defining the JDBC URL property:[source, properties]
quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/hibernate_orm_test
请注意属性名称中的 Note the |
有关配置 JDBC 的更多信息,请参阅 JDBC URL format reference和 Quarkus extensions and database drivers reference。
For more information about configuring JDBC, see jdbc-url and extensions-and-database-drivers-reference.
Custom databases and drivers
如果你需要连接到一个数据库,但 Quarkus 没有提供带有 JDBC 驱动的扩展,你可以改为使用一个自定义驱动。例如,如果你在你的项目中使用了 OpenTracing JDBC 驱动。
If you need to connect to a database for which Quarkus does not provide an extension with the JDBC driver, you can use a custom driver instead. For example, if you are using the OpenTracing JDBC driver in your project.
如果没有扩展,该驱动在以 JVM 模式运行的任何 Quarkus 应用程序中都能正常工作。但是,当把你的应用程序编译成原生可执行文件时,该驱动很可能无法工作。如果你计划制作一个原生可执行文件,请使用现有的 JDBC Quarkus 扩展,或为你的驱动贡献一个。
Without an extension, the driver will work correctly in any Quarkus app running in JVM mode. However, the driver is unlikely to work when compiling your application to a native executable. If you plan to make a native executable, use the existing JDBC Quarkus extensions, or contribute one for your driver.
OpenTracing 已弃用,取而代之的是 OpenTelemetry。有关跟踪信息,请查看下面的 Datasource tracing相关部分。
OpenTracing has been deprecated in favor of OpenTelemetry. For tracing information, please check the related section about Datasource tracing, bellow.
quarkus.datasource.jdbc.driver=io.opentracing.contrib.jdbc.TracingDriver
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部分。
For all the details about the JDBC configuration options and configuring other aspects, such as the connection pool size, refer to the jdbc-configuration section.
Consuming the datasource
使用 Hibernate ORM 时,Hibernate 层会自动获取数据源并使用它。
With Hibernate ORM, the Hibernate layer automatically picks up the datasource and uses it.
若要在代码中访问数据源,像获取任何其他 bean 一样获取它,如下所示:
For the in-code access to the datasource, obtain it as any other bean as follows:
@Inject
AgroalDataSource defaultDataSource;
在上面的示例中,类型是 AgroalDataSource
,它是 `javax.sql.DataSource`的子类型。因此,你也可以使用 `javax.sql.DataSource`作为注入的类型。
In the above example, the type is AgroalDataSource
, a javax.sql.DataSource
subtype.
Because of this, you can also use javax.sql.DataSource
as the injected type.
Reactive datasource
Quarkus 提供了多个反应式客户端,可与反应式数据源一起使用。
Quarkus offers several reactive clients for use with a reactive datasource.
-
Add the corresponding extension to your application:
-
DB2:
quarkus-reactive-db2-client
-
MariaDB/MySQL:
quarkus-reactive-mysql-client
-
Microsoft SQL Server:
quarkus-reactive-mssql-client
-
Oracle:
quarkus-reactive-oracle-client
-
PostgreSQL:
quarkus-reactive-pg-client
[.iokays-translated-8e2091d9bf62c4f5bd26df505b7e61c5] 已安装的扩展必须与你在数据源配置中定义的 `quarkus.datasource.db-kind`一致。
-
The installed extension must be consistent with the quarkus.datasource.db-kind
you define in your datasource configuration.
-
After adding the driver, configure the connection URL and define a proper size for your connection pool.[source, properties]
quarkus.datasource.reactive.url=postgresql:///your_database quarkus.datasource.reactive.max-size=20
Reactive connection pool size adjustment
为了在负载高峰期间保护你的数据库免于过载,请适当调整池大小,以限制数据库负载。适当的大小总取决于许多因素,例如并发应用程序用户数或工作负载的性质。
To protect your database from overloading during load peaks, size the pool adequately to throttle the database load. The proper size always depends on many factors, such as the number of parallel application users or the nature of the workload.
请注意,设置过小的连接池大小可能会导致一些请求在等待连接时超时。
Be aware that setting the pool size too low might cause some requests to time out while waiting for a connection.
有关池大小调整属性的更多信息,请参阅 Reactive datasource configuration reference部分。
For more information about pool size adjustment properties, see the Reactive datasource configuration reference section.
JDBC and reactive datasources simultaneously
当同时包含一个 JDBC 扩展(与 Agroal 一起)和一个处理给定数据库类型的反应式数据源扩展时,它们都将默认创建。
When a JDBC extension - along with Agroal - and a reactive datasource extension handling the given database kind are included, they will both be created by default.
If you want to use them both, make sure to set both jdbc-datasource and reactive-datasource configuration, for example:
%prod.quarkus.datasource.reactive.url=postgresql:///your_database
%prod.quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/hibernate_orm_test
如果你不想创建 JDBC 数据源和反应式数据源,请使用以下配置。* 显式禁用 JDBC 数据源:
If you do not want to have both a JDBC datasource and a reactive datasource created, use the following configuration. * To disable the JDBC datasource explicitly:
+
quarkus.datasource.jdbc=false
-
To disable the reactive datasource explicitly:[source, properties]
quarkus.datasource.reactive=false
在大多数情况下,上述配置是可选的,因为既不会存在 JDBC 驱动程序,也不会存在反应式数据源扩展,两者不会共存。 In most cases, the configuration above will be optional as either a JDBC driver or a reactive datasource extension will be present, not both. |
Configure multiple datasources
Hibernate ORM 扩展支持通过配置属性定义 persistence units。对于每个持久性单元,请指向您选择的 datasource。 The Hibernate ORM extension supports defining persistence units by using configuration properties. For each persistence unit, point to the datasource of your choice. |
定义多个 datasource 的方式与定义单个 datasource 的方式类似,但有一个重要的区别 - 您必须为每个 datasource 指定一个名称 (配置属性)。
Defining multiple datasources works like defining a single datasource, with one important change - you have to specify a name (configuration property) for each datasource.
以下示例提供了三个不同的 datasource:
The following example provides three different datasources:
-
the default one
-
a datasource named
users
-
a datasource named
inventory
每个都有其配置:
Each with its configuration:
quarkus.datasource.db-kind=h2
quarkus.datasource.username=username-default
quarkus.datasource.jdbc.url=jdbc:h2:mem:default
quarkus.datasource.jdbc.max-size=13
quarkus.datasource.users.db-kind=h2
quarkus.datasource.users.username=username1
quarkus.datasource.users.jdbc.url=jdbc:h2:mem:users
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:mem:inventory
quarkus.datasource.inventory.jdbc.max-size=12
请注意,配置属性中有一个额外的部分。语法如下: quarkus.datasource.[optional name.][datasource property]
。
Notice there is an extra section in the configuration property.
The syntax is as follows: quarkus.datasource.[optional name.][datasource property]
.
即使只安装了一个数据库扩展,已命名的数据库也需要指定至少一个构建时属性,以便 Quarkus 能够检测到它们。通常,这是 `db-kind`属性,但您也可以指定开发服务属性来根据 Dev Services for Databases指南创建已命名的 datasource。 |
Even when only one database extension is installed, named databases need to specify at least one build-time property so that Quarkus can detect them.
Generally, this is the |
Named datasource injection
使用多个 datasource 时,每个 `DataSource`还带有 `io.quarkus.agroal.DataSource`限定符,其值是 datasource 的名称。
When using multiple datasources, each DataSource
also has the io.quarkus.agroal.DataSource
qualifier with the name of the datasource as the value.
通过使用上一部分中提到的属性配置三个不同的 datasource,如下注入每个datasource:
By using the properties mentioned in the previous section to configure three different datasources, inject each one of them as follows:
@Inject
AgroalDataSource defaultDataSource;
@Inject
@DataSource("users")
AgroalDataSource usersDataSource;
@Inject
@DataSource("inventory")
AgroalDataSource inventoryDataSource;
Activate/deactivate datasources
如果在构建时配置了某个 datasource,则默认情况下它在运行时处于活动状态,即 Quarkus 会在应用程序启动时启动相应的 JDBC 连接池或反应式客户端。
If a datasource is configured at build time, by default it is active at runtime, that is Quarkus will start the corresponding JDBC connection pool or reactive client on application startup.
要在运行时停用某个 datasource,请将 quarkus.datasource[.optional name].active`设置为 `false
。然后 Quarkus 将不会在应用程序启动时启动相应的 JDBC 连接池或反应式客户端。在运行时使用相应 datasource 的任何尝试都将失败,并显示一条明确的错误消息。
To deactivate a datasource at runtime, set quarkus.datasource[.optional name].active
to false
.
Then Quarkus will not start the corresponding JDBC connection pool or reactive client on application startup.
Any attempt to use the corresponding datasource at runtime will fail with a clear error message.
这在您希望应用程序能够在运行时使用预先确定的 datasource 集中的一项 datasource 时尤为有用。
This is in particular useful when you want an application to be able to use one of a pre-determined set of datasources at runtime.
如果另一个 Quarkus 扩展依赖于一个不活动的数据源,那么该扩展可能会启动失败。
If another Quarkus extension relies on an inactive datasource, that extension might fail to start.
在这种情况下,您还需要停用该其他扩展。例如,请参见 here for Hibernate ORM。
In such case, you will need to deactivate that other extension too. For example see here for Hibernate ORM.
例如,使用以下配置:
For example, with the following configuration:
quarkus.datasource."pg".db-kind=postgres
quarkus.datasource."pg".active=false
quarkus.datasource."pg".jdbc.url=jdbc:postgresql:///your_database
quarkus.datasource."oracle".db-kind=oracle
quarkus.datasource."oracle".active=false
quarkus.datasource."oracle".jdbc.url=jdbc:oracle:///your_database
设置 `quarkus.datasource."pg".active=true`at runtime将仅使 PostgreSQL 数据源可用,并在运行时设置 `quarkus.datasource."oracle".active=true`将仅使 Oracle 数据源可用。
Setting quarkus.datasource."pg".active=true
at runtime
will make only the PostgreSQL datasource available,
and setting quarkus.datasource."oracle".active=true
at runtime
will make only the Oracle datasource available.
Custom configuration profiles可以帮助简化这样的设置。通过将以下特定于配置文件的配置附加到上面的配置,您可以简单地通过 setting Custom configuration profiles can help simplify such a setup.
By appending the following profile-specific configuration to the one above,
you can select a persistence unit/datasource at runtime simply by
setting
|
定义一个重定向到当前活动数据源的 CDI bean producer也很有用,如下所示: It can also be useful to define a CDI bean producer redirecting to the currently active datasource, like this:
|
Use multiple datasources in a single transaction
默认情况下,数据源上的 XA 支持被禁用,因此一个事务最多可以包含一个数据源。尝试在同一事务中访问多个非 XA 数据源将导致类似于此的异常:
By default, XA support on datasources is disabled, and thus a transaction may include at most one datasource. Attempting to access multiple non-XA datasources in the same transaction would result in an exception similar to this:
...
Caused by: java.sql.SQLException: Exception in association of connection to existing transaction
at io.agroal.narayana.NarayanaTransactionIntegration.associate(NarayanaTransactionIntegration.java:130)
...
Caused by: java.sql.SQLException: Failed to enlist. Check if a connection from another datasource is already enlisted to the same transaction
at io.agroal.narayana.NarayanaTransactionIntegration.associate(NarayanaTransactionIntegration.java:121)
...
若要允许在同一事务中使用多个 JDBC 数据源:
To allow using multiple JDBC datasources in the same transaction:
-
Make sure your JDBC driver supports XA. All extensions-and-database-drivers-reference, but other-databases might not.
-
Make sure your database server is configured to enable XA.
-
Enable XA support explicitly for each relevant datasource by setting <<`quarkus.datasource[.optional name].jdbc.transactions`,quarkus-agroal_quarkus-datasource-jdbc-transactions>> to
xa
.
使用 XA,一个数据源中的回滚将触发事务中注册的每个其他数据源中的回滚。
Using XA, a rollback in one datasource will trigger a rollback in every other datasource enrolled in the transaction.
当前不支持反应性数据源上的 XA 事务。 XA transactions on reactive datasources are not supported at the moment. |
如果事务涉及其他非数据源资源,请记住 *those*资源可能不支持 XA 事务或可能需要其他配置。 If your transaction involves other, non-datasource resources, keep in mind those resources might not support XA transactions, or might require additional configuration. |
如果无法为数据源之一启用 XA:
If XA cannot be enabled for one of your datasources:
-
Be aware that enabling XA for all datasources except one (and only one) is still supported through Last Resource Commit Optimization (LRCO).
-
If you do not need a rollback for one datasource to trigger a rollback for other datasources, consider splitting your code into multiple transactions. To that end, use
QuarkusTransaction.requiringNew()
/@Transactional(REQUIRES_NEW)
(preferably) orUserTransaction
(for more complex use cases).
作为最后的手段,为了与 Quarkus 3.8 及更低版本兼容,你可以通过将 `quarkus.transaction-manager.unsafe-multiple-last-resources`设置为 `allow`来允许跨多个非 XA 数据源进行不安全的交易处理。
As a last resort, and for compatibility with Quarkus 3.8 and earlier,
you may allow unsafe transaction handling across multiple non-XA datasources
by setting quarkus.transaction-manager.unsafe-multiple-last-resources
to allow
.
使用此属性设置为 allow
,事务回滚可能只适用于其中一些非 XA 数据源,其他非 XA 数据源可能已经提交其更改,进而使整个系统处于不一致的状态。
With this property set to allow
, a transaction rollback
could possibly be applied to only some of the non-XA datasources,
with other non-XA datasources having already committed their changes,
leaving your overall system in an inconsistent state.
或者,你可以允许相同的 unsafe 行为,但当利用此行为时发出警告:
Alternatively, you can allow the same unsafe behavior, but with warnings when it is taken advantage of:
-
setting the property to
warn-each
would result in logging a warning on each offending transaction. -
setting the property to
warn-first
would result in logging a warning on the first offending transaction.
我们不建议使用此配置属性,并且我们计划在未来将其删除,因此你应计划相应修复应用程序。如果你认为此功能的用例有效,并且应该保留此选项,请在 Quarkus tracker 中打开一个 issue 并说明原因。
We do not recommend using this configuration property, and we plan to remove it in the future, so you should plan fixing your application accordingly. If you think your use case of this feature is valid and this option should be kept around, open an issue in the Quarkus tracker explaining why.
Datasource integrations
Datasource health check
如果您使用 quarkus-smallrye-health
扩展,则 `quarkus-agroal`和反应客户端扩展会自动添加一个就绪性检查以验证数据源。
If you use the quarkus-smallrye-health
extension, the quarkus-agroal
and reactive client extensions automatically add a readiness health check to validate the datasource.
当您访问应用程序的运行就绪状态端点时,/q/health/ready`默认显示有关数据源验证状态的信息。如果您有多个数据源,则会检查所有数据源,并且只要发生单个数据源验证失败,状态就会变为 `DOWN
。
When you access your application’s health readiness endpoint, /q/health/ready
by default, you receive information about the datasource validation status.
If you have multiple datasources, all datasources are checked, and if a single datasource validation failure occurs, the status changes to DOWN
.
使用 `quarkus.datasource.health.enabled`属性可以禁用此行为。
This behavior can be disabled by using the quarkus.datasource.health.enabled
property.
若要只从运行状况检查中排除某个特定数据源,请使用:
To exclude only a particular datasource from the health check, use:
quarkus.datasource."datasource-name".health-exclude=true
Datasource metrics
如果您使用的是 quarkus-micrometer
或 quarkus-smallrye-metrics
扩展,`quarkus-agroal`可以将一些与数据源相关指标添加到指标注册表。这可以通过将 `quarkus.datasource.metrics.enabled`属性设置为 `true`来激活。
If you are using the quarkus-micrometer
or quarkus-smallrye-metrics
extension, quarkus-agroal
can contribute some datasource-related metrics to the metric registry.
This can be activated by setting the quarkus.datasource.metrics.enabled
property to true
.
若要使所公开的指标包含任何实际值,则必须在内部由 Agroal 机制启用指标收集。默认情况下,当存在指标扩展并且启用了 Agroal 扩展的指标时,针对所有数据源启用了该指标收集机制。
For the exposed metrics to contain any actual values, a metric collection must be enabled internally by the Agroal mechanisms. By default, this metric collection mechanism is enabled for all datasources when a metrics extension is present, and metrics for the Agroal extension are enabled.
要禁用特定数据源的指标,请将 quarkus.datasource.jdbc.enable-metrics`设置为 `false
,或者对已命名数据源应用 quarkus.datasource.<datasource name>.jdbc.enable-metrics
。如果禁用收集这些指标的机制,这将禁用收集指标并在 `/q/metrics`端点中公开指标。
To disable metrics for a particular data source,
set quarkus.datasource.jdbc.enable-metrics
to false
, or apply quarkus.datasource.<datasource name>.jdbc.enable-metrics
for a named datasource.
This disables collecting the metrics and exposing them in the /q/metrics
endpoint if the mechanism to collect them is disabled.
相反,将 quarkus.datasource.jdbc.enable-metrics`设置为 `true
,或者对已命名数据源使用 `quarkus.datasource.<datasource name>.jdbc.enable-metrics`将会显式启用指标收集,即使没有使用指标扩展也是如此。如果您需要以编程方式访问收集到的指标,这将非常有用。您可以通过对注入的 `AgroalDataSource`实例调用 `dataSource.getMetrics()`来获得指标。
Conversely, setting quarkus.datasource.jdbc.enable-metrics
to true
, or quarkus.datasource.<datasource name>.jdbc.enable-metrics
for a named datasource explicitly enables metrics collection even if a metrics extension is not in use.
This can be useful if you need to access the collected metrics programmatically.
They are available after calling dataSource.getMetrics()
on an injected AgroalDataSource
instance.
如果禁用此数据源的指标收集,则所有值都将为零。
If the metrics collection for this datasource is disabled, all values result in zero.
Datasource tracing
要对数据源使用跟踪,您需要将 quarkus-opentelemetry
扩展添加到您的项目。
To use tracing with a datasource, you need to add the quarkus-opentelemetry
extension to your project.
不需要声明不同的驱动程序,因为您需要跟踪。如果您使用 JDBC 驱动程序,则需要按照 OpenTelemetry 扩展 here中的说明操作。
You don’t need to declare a different driver because you need tracing. If you use a JDBC driver, you need to follow the instructions in the OpenTelemetry extension here.
即使所有跟踪基础设施都已到位,数据源跟踪也默认不会启用,您需要通过设置此属性来启用它:
Even with all the tracing infrastructure in place the datasource tracing is not enabled by default, and you need to enable it by setting this property:
# enable tracing
quarkus.datasource.jdbc.telemetry=true
Narayana transaction manager integration
如果 Narayana JTA 扩展也可用,则集成是自动的。
Integration is automatic if the Narayana JTA extension is also available.
您可以通过设置 `transactions`配置属性来覆盖此内容:
You can override this by setting the transactions
configuration property:
-
quarkus.datasource.jdbc.transactions
for default unnamed datasource -
quarkus.datasource.<datasource-name>.jdbc.transactions
for named datasource
有关更多信息,请参阅下面的 Configuration reference部分。
For more information, see the configuration-reference section below.
要通过使用 JDBC 在数据库中存储事务日志,请参阅 Using transactions in Quarkus指南的 Configuring transaction logs to be stored in a datasource部分。
To facilitate the storage of transaction logs in a database by using JDBC, see Configuring transaction logs to be stored in a datasource section of the Using transactions in Quarkus guide.
Named datasources
使用开发人员服务时,总是会创建默认数据源,但要指定已命名数据源,您需要至少有一个构建时间属性,以便 Quarkus 可以检测如何创建数据源。
When using Dev Services, the default datasource will always be created, but to specify a named datasource, you need to have at least one build time property so Quarkus can detect how to create the datasource.
您通常会指定 `db-kind`属性或通过设置 `quarkus.datasource."name".devservices.enabled=true`显式启用 Dev Services。
You will usually specify the db-kind
property or explicitly enable Dev Services by setting quarkus.datasource."name".devservices.enabled=true
.
Testing with in-memory databases
一些数据库(例如 H2 和 Derby)通常在 embedded mode 中用作快速运行集成测试的工具。
Some databases like H2 and Derby are commonly used in the embedded mode as a facility to run integration tests quickly.
建议的方法是使用你打算在生产中使用的真实数据库,尤其是在 Dev Services provide a zero-config database for testing 时,针对容器运行测试相对较快,并在实际环境中产生预期结果。不过,在需要运行简单集成测试时也可以使用受 JVM 支持的数据库。
The recommended approach is to use the real database you intend to use in production, especially when Dev Services provide a zero-config database for testing, and running tests against a container is relatively quick and produces expected results on an actual environment. However, it is also possible to use JVM-powered databases for scenarios when the ability to run simple integration tests is required.
Support and limitations
嵌入式数据库(H2 和 Derby)在 JVM 模式下工作。对于原生模式,适用以下限制:
Embedded databases (H2 and Derby) work in JVM mode. For native mode, the following limitations apply:
-
Derby cannot be embedded into the application in native mode. However, the Quarkus Derby extension allows native compilation of the Derby JDBC client, supporting remote connections.
-
Embedding H2 within your native image is not recommended. Consider using an alternative approach, for example, using a remote connection to a separate database instead.
Run an integration test
-
Add a dependency on the artifacts providing the additional tools that are under the following Maven coordinates:
-
io.quarkus:quarkus-test-h2
for H2 -
io.quarkus:quarkus-test-derby
for Derby[.iokays-translated-482cc2312cb7102c74024e7c9dd88cc7] 这将允许你在应用程序编译成原生可执行文件时对其进行测试,而数据库将作为 JVM 进程运行。
-
This will allow you to test your application even when it is compiled into a native executable while the database will run as a JVM process.
-
Add the following specific annotation on any class in your integration tests for running integration tests in both JVM or native executables:
-
@WithTestResource(H2DatabaseTestResource.class)
-
@WithTestResource(DerbyDatabaseTestResource.class)
[.iokays-translated-5f27ba45d9aa5e5b4fbe2114ae0ec983] 这确保测试套件将管理的数据库作为测试执行所需的单独进程来启动和终止。
-
This ensures that the test suite starts and terminates the managed database in a separate process as required for test execution.
package my.app.integrationtests.db;
import io.quarkus.test.common.WithTestResource;
import io.quarkus.test.h2.H2DatabaseTestResource;
@WithTestResource(H2DatabaseTestResource.class)
public class TestResources {
}
-
Configure the connection to the managed database:[source, properties]
quarkus.datasource.db-kind=h2 quarkus.datasource.jdbc.url=jdbc:h2:tcp://localhost/mem:test
References
Common datasource configuration reference
Unresolved directive in datasource.adoc - include::{generated-dir}/config/quarkus-datasource.adoc[]
JDBC configuration reference
Unresolved directive in datasource.adoc - include::{generated-dir}/config/quarkus-agroal.adoc[]
JDBC URL reference
每个受支持的数据库都包含不同的 JDBC URL 配置选项。以下部分概述了每个数据库 URL,并链接到官方文档。
Each of the supported databases contains different JDBC URL configuration options. The following section gives an overview of each database URL and a link to the official documentation.
DB2
jdbc:db2://<serverName>[:<portNumber>]/<databaseName>[:<key1>=<value>;[<key2>=<value2>;]]
jdbc:db2://<serverName>[:<portNumber>]/<databaseName>[:<key1>=<value>;[<key2>=<value2>;]]
- Example
-
jdbc:db2://localhost:50000/MYDB:user=dbadm;password=dbadm;
有关 URL 语法的更多信息和其他受支持的选项,请参阅 official documentation。
For more information on URL syntax and additional supported options, see the official documentation.
Derby
jdbc:derby:[//serverName[:portNumber]/][memory:]databaseName[;property=value[;property=value]]
- Example
-
jdbc:derby://localhost:1527/myDB
,jdbc:derby:memory:myDB;create=true
Derby 是一款嵌入式数据库,可以作为服务器运行、以文件为基础运行,或者完全在内存中运行。所有这些选项都可用,如上所列。
Derby is an embedded database that can run as a server, based on a file, or can run completely in memory. All of these options are available as listed above.
有关更多信息,请参阅 official documentation。
For more information, see the official documentation.
H2
jdbc:h2:{ {.|mem:}[name] | [file:]fileName | {tcp|ssl}:[//]server[:port][,server2[:port]]/name }[;key=value…]
- Example
-
jdbc:h2:tcp://localhost/~/test
,jdbc:h2:mem:myDB
H2 是一个可以以嵌入式或服务器模式运行的数据库。它可以使用文件存储或完全在内存中运行。列出的所有选项都可用。
H2 is a database that can run in embedded or server mode. It can use a file storage or run entirely in memory. All of these options are available as listed above.
有关详细信息,请参阅 official documentation。
For more information, see the official documentation.
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:[replication:|failover:|sequential:|aurora:]//<hostDescription>[,<hostDescription>…]/[database][?<key1>=<value1>[&<key2>=<value2>]]
hostDescription:: <host>[:<portnumber>] or address=(host=<host>)[(port=<portnumber>)][(type=(master|slave))]
- Example
-
jdbc:mariadb://localhost:3306/test
有关详细信息,请参阅 official documentation。
For more information, see the official documentation.
Microsoft SQL server
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
- Example
-
jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks
Microsoft SQL Server JDBC 驱动程序的工作原理基本上与其他驱动程序相同。
The Microsoft SQL Server JDBC driver works essentially the same as the others.
有关详细信息,请参阅 official documentation。
For more information, see the official documentation.
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:[replication:|failover:|sequential:|aurora:]//<hostDescription>[,<hostDescription>…]/[database][?<key1>=<value1>[&<key2>=<value2>]]
hostDescription:: <host>[:<portnumber>] or address=(host=<host>)[(port=<portnumber>)][(type=(master|slave))]
- Example
-
jdbc:mysql://localhost:3306/test
有关详细信息,请参阅 official documentation。
For more information, see the official documentation.
MySQL limitations
在将 Quarkus 应用程序编译为本机映像时,MySQL 对 JMX 和 Oracle Cloud Infrastructure (OCI) 集成的支持处于禁用状态,因为它们与 GraalVM 本机映像不兼容。
When compiling a Quarkus application to a native image, the MySQL support for JMX and Oracle Cloud Infrastructure (OCI) integrations are disabled as they are incompatible with GraalVM native images.
-
The lack of JMX support is a natural consequence of running in native mode and is unlikely to be resolved.
-
The integration with OCI is not supported.
Oracle
jdbc:oracle:driver_type:@database_specifier
- Example
-
jdbc:oracle:thin:@localhost:1521/ORCL_SVC
有关详细信息,请参阅 official documentation。
For more information, see the official documentation.
PostgreSQL
jdbc:postgresql:[//][host][:port][/database][?key=value…]
- Example
-
jdbc:postgresql://localhost/test
不同部分的默认值如下:
The defaults for the different parts are as follows:
host
-
localhost
port
-
5432
database
-
same name as the username
有关其他参数的详细信息,请参阅 official documentation。
For more information about additional parameters, see the official documentation.
Quarkus extensions and database drivers reference
下表列出了内置 db-kind
值、相应的 Quarkus 扩展以及这些扩展使用的 JDBC 驱动程序。
The following tables list the built-in db-kind
values, the corresponding Quarkus extensions, and the JDBC drivers used by those extensions.
使用其中一种内置 datasource 类型时,JDBC 和 Reactive 驱动程序会自动解析为与这些表的中的值匹配。
When using one of the built-in datasource kinds, the JDBC and Reactive drivers are resolved automatically to match the values from these tables.
Database kind | Quarkus extension | Drivers |
---|---|---|
|
|
* JDBC: * XA: |
|
|
* JDBC: * XA: |
|
|
* JDBC: * XA: |
|
|
* JDBC: * XA: |
|
|
* JDBC: * XA: |
|
|
* JDBC: * XA: |
|
|
* JDBC: * XA: |
|
|
* JDBC: * XA: |
Database kind | Quarkus extension | Driver |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
在大多数情况下,此自动解决办法适用,因此无需驱动器配置。 This automatic resolution is applicable in most cases so that driver configuration is not needed. |
Reactive datasource configuration reference
Unresolved directive in datasource.adoc - include::{generated-dir}/config/quarkus-reactive-datasource.adoc[]
Reactive DB2 configuration
Unresolved directive in datasource.adoc - include::{generated-dir}/config/quarkus-reactive-db2-client.adoc[]
Reactive MariaDB/MySQL specific configuration
Unresolved directive in datasource.adoc - include::{generated-dir}/config/quarkus-reactive-mysql-client.adoc[]
Reactive Microsoft SQL server-specific configuration
Unresolved directive in datasource.adoc - include::{generated-dir}/config/quarkus-reactive-mssql-client.adoc[]
Reactive datasource URL reference
DB2
db2://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
db2://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
- Example
-
db2://dbuser:secretpassword@database.server.com:50000/mydb
目前,客户端支持以下参数键:
Currently, the client supports the following parameter keys:
-
host
-
port
-
user
-
password
-
database
在连接 URL 中配置参数将覆盖默认属性。 |
Configuring parameters in the connection URL overrides the default properties. |
Microsoft SQL server
sqlserver://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
sqlserver://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
- Example
-
sqlserver://dbuser:secretpassword@database.server.com:1433/mydb
目前,客户端支持以下参数键:
Currently, the client supports the following parameter keys:
-
host
-
port
-
user
-
password
-
database
在连接 URL 中配置参数将覆盖默认属性。 |
Configuring parameters in the connection URL overrides the default properties. |
MySQL / MariaDB
mysql://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
mysql://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
- Example
-
mysql://dbuser:secretpassword@database.server.com:3211/mydb
目前,客户端支持以下参数键(不区分大小写):
Currently, the client supports the following parameter keys (case-insensitive):
-
host
-
port
-
user
-
password
-
schema
-
socket
-
useAffectedRows
在连接 URL 中配置参数将覆盖默认属性。 |
Configuring parameters in the connection URL overrides the default properties. |
Oracle
PostgreSQL
postgresql://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
postgresql://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
- Example
-
postgresql://dbuser:secretpassword@database.server.com:5432/mydb
目前,客户端支持:
Currently, the client supports:
-
Following parameter keys:
-
host
-
port
-
user
-
password
-
dbname
-
sslmode
-
-
Additional properties, such as:
-
application_name
-
fallback_application_name
-
search_path
-
options
-
在连接 URL 中配置参数将覆盖默认属性。 |
Configuring parameters in the connection URL overrides the default properties. |