Quarkusでデータソースを設定
統一された設定モデルを使用して、Java Database Connectivity (JDBC) および Reactive ドライバーのデータソースを定義します。
アプリケーションは、データソースを使用してリレーショナルデータベースにアクセスします。 Quarkusは、Java Database Connectivity(JDBC)およびReactiveデータベースドライバー用のデータソースを定義するための統一された設定モデルを提供します。
Quarkusは、Agroal と Vert.x を使用して、JDBC とリアクティブドライバー用の高性能でスケーラブルなデータソース接続プーリングを提供します。
quarkus-jdbc-*
および quarkus-reactive-*-client
のエクステンションは、ビルド時最適化を提供し、設定されたデータソースを、セキュリティー、ヘルスチェック、メトリクスなどの Quarkus の機能と統合します。
リアクティブデータソースの消費と使用に関する詳細は、Quarkus Reactive SQLクライアントガイド を参照してください。
さらに、JDBCデータソースの消費と使用については、Quarkus Hibernate ORM ガイドを参照してください。
Quarkusでの datasources
の設定入門
このセクションでは、基礎を理解しているユーザー向けに、データソースをすばやく設定するための概要とコードサンプルを示します。
より高度な設定とその例については、参照 を参照してください。
開発モードでのゼロコンフィグセットアップ
Quarkusでは、Dev Services機能によってデータベース設定が簡素化され、テストや開発(dev)モードでの実行のためのデータベース設定をゼロコンフィギュレーションで行うことができます。 開発モードでは、DevServicesを使用してQuarkusにデータベースを処理させる方法が推奨されます。一方、本番モードでは、Quarkusの外部で管理されるデータベースを指す明示的なデータベース設定の詳細を記述してください。
Dev Services を使用するには、pom.xml
ファイルに、希望するデータベースタイプに適したドライバーエクステンション (jdbc-postgresql
など) を追加します。
開発モードでは、明示的なデータベース接続の詳細を記述しない場合、Quarkus が自動的にデータベースのセットアップを行い、アプリケーションとデータベース間の接続を行います。
ユーザークレデンシャルを指定すると、基礎となるデータベースはそのクレデンシャルを使用するように設定されます。 これは、外部ツールでデータベースに接続したい場合に便利です。
この機能を使用するには、データベースの種類に応じて、Docker または Podman コンテナーランタイムがインストールされていることを確認してください。 H2 などの特定のデータベースはインメモリモードで動作するため、コンテナーランタイムは必要ありません。
本番モードの実際の接続詳細の前に %prod. を付けて、それらが開発モードで適用されないようにします。
詳細は、「設定リファレンス」の プロファイル セクションを参照してください。
|
Dev Services の詳細については、 Dev Services の概要 を参照してください。
詳細およびオプション設定については、 Dev Services for databases を参照してください。
JDBC データソースの設定
-
選択したデータベースの正しい JDBC エクステンションを追加します。
-
quarkus-jdbc-db2
-
quarkus-jdbc-derby
-
quarkus-jdbc-h2
-
quarkus-jdbc-mariadb
-
quarkus-jdbc-mssql
-
quarkus-jdbc-mysql
-
quarkus-jdbc-oracle
-
quarkus-jdbc-postgresql
-
-
JDBC データソースを設定します:
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 この設定値は、クラスパスに複数のデータベースエクステンションがある場合にのみ必要です。
使用可能なエクステンションが1つしかない場合、Quarkusはこれを正しいエクステンションとみなします。 テストスコープにドライバーを追加すると、Quarkusは自動的に指定したドライバーをテストに含めます。
JDBC接続プールのサイズ調整
負荷のピーク時の過負荷からデータベースを保護するには、データベースの負荷を軽減するためにプールのサイズを適切に設定します。 最適なプールのサイズは、並列アプ リ ケーシ ョ ンのユーザー数や作業負荷の性質な ど、 さ ま ざ ま な要因に よ っ て異な り ます。
プールサイズを小さく設定しすぎると、接続待ちの間にタイムアウトする リクエストが出てくるかもしれないことに注意してください。
プールサイズ調整プロパティーの詳細は、JDBC 設定リファレンス セクションを参照してください。
Reactiveデータソースの設定
-
選択したデータベースの正しいリアクティブエクステンションを追加します。
-
quarkus-reactive-db2-client
-
quarkus-reactive-mssql-client
-
quarkus-reactive-mysql-client
-
quarkus-reactive-oracle-client
-
quarkus-reactive-pg-client
-
-
リアクティブデータソースを設定します:
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 この設定値は、クラスパスに複数の Reactive ドライバーエクステンションがある場合にのみ必要です。
データソースの設定
以下のセクションでは、単一または複数のデータソースの設定について説明します。 ここでは簡単のため、単一のデータソースをデフォルトの (無名の) データソースとして参照します。
単一のデータソースの設定
データソースには、JDBC データソース、リアクティブ、またはその両方を指定できます。 これは、設定とプロジェクトエクステンションの選択に依存します。
-
以下の設定プロパティーでデータソースを定義します。
db-kind
は、どのデータベースプラットフォームに接続するかを定義します。例えば、h2
の場合:quarkus.datasource.db-kind=h2
Quarkusは、
db-kind
データベースプラットフォーム属性の指定値から、使用するJDBCドライバークラスを推測します。この手順は、アプリケーションが複数のデータベースドライバーに依存している場合にのみ必要です。 アプリケーションが単一のドライバーで動作する場合、このドライバーは自動的に検出されます。 Quarkusには現在、以下のデータベースのdb-kindが組み込まれています:
-
DB2:
db2
-
Derby:
derby
-
H2:
h2
-
MariaDB:
mariadb
-
Microsoft SQL Server:
mssql
-
MySQL:
mysql
-
Oracle:
oracle
-
PostgreSQL:
postgresql
、pgsql
、またはpg
-
ビルトインされていない種類のデータベースを使用するには、
other
を使用し、JDBC ドライバーを明示的に定義します。Custom databases and drivers に記載されているように、Quarkus アプリケーションでは、JVM モードで任意の JDBC ドライバーを使用できます。 ただし、アプリケーションをネイティブ実行可能ファイルにコンパイルするときに、組み込みではないデータベースの種類を使用すると、機能しない可能性があります。
ネイティブ実行可能ファイルをビルドする場合は、利用可能なJDBC Quarkusエクステンションを使用するか、特定のドライバー用にカスタムエクステンションを作成することをお勧めします。
-
-
以下のプロパティーを設定し、クレデンシャルを定義します:
quarkus.datasource.username=<your username> quarkus.datasource.password=<your password>
また、データソースに クレデンシャルプロバイダを使用することで、Vault からパスワードを取得することもできます。
これまでは、JDBC ドライバーと Reactive ドライバーのどちらを使用していても、設定は同じでした。 データベースの種類とクレデンシャルを定義したら、あとは使用するドライバーの種類に依存します。 JDBC とReactive ドライバーを同時に使用することは可能です。
JDBC データソース
JDBC は最も一般的なデータベース接続パターンで、典型的には非リアクティブ型の Hibernate ORM と組み合わせて使用する場合に必要となります。
-
JDBC データソースを使用するには、必要な依存関係を追加することから始めます:
-
組み込みの JDBC ドライバーで使用する場合は、以下のリストからリレーショナルデータベースドライバー用の Quarkus エクステンションを選択して追加します。
-
Derby -
quarkus-jdbc-derby
-
H2 -
quarkus-jdbc-h2
H2およびDerbyデータベースは、"組み込みモード "で実行するように設定することができます。しかし、Derbyエクステンションは、組み込みデータベースエンジンをネイティブ実行可能ファイルにコンパイルすることをサポートしていません。
インテグレーションテストに関する提案については、Testing with in-memory databases を参照してください。
-
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
-
その他のJDBCエクステンション (SQLite およびその ドキュメントなど) は、https://github.com/quarkiverse[Quarkiverse] にあります。
例えば、PostgreSQLドライバー依存関係を追加します:
./mvnw quarkus:add-extension -Dextensions="jdbc-postgresql"
組込JDBC ドライバーのエクステンションを使用すると、カスタムと組込JDBC ドライバーに適用可能な JDBC 接続プールの実装である Agroal エクステンションが自動的に含まれます。 しかし、カスタムドライバーの場合、Agroal を明示的に追加する必要があります。
-
-
カスタム JDBC ドライバーと共に使用する場合は、リレーショナルデータベースドライバーのエクステンションと一緒に、
quarkus-agroal
依存関係をプロジェクトに追加します:./mvnw quarkus:add-extension -Dextensions="agroal"
別のデータベースの JDBC ドライバーを使用するには、use a database with no built-in extension or with a different driver 組み込みのエクステンションがないデータベース、または異なるドライバーを使用するデータベースを利用してください。
-
-
JDBC URL プロパティーを定義して、JDBC 接続を構成します:
quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/hibernate_orm_test
プロパティー名の接頭辞
jdbc
に注意してください。 JDBC 固有の設定プロパティーにはすべて、接頭語にjdbc
が付きます。 Reactive データソースの場合、接頭辞はreactive
です。
JDBC の設定の詳細は、JDBC URL format reference および Quarkus extensions and database drivers reference を参照してください。
カスタムデータベースとドライバー
Quarkus がデータベース用の JDBC エクステンションを提供していない場合、または OpenTelemetry 用などの別の JDBC ドライバーを使用する必要がある場合は、JDBC ドライバーを明示的に設定できます。
エクステンションがない場合、JDBC ドライバーは JVM モードで正しく動作することが期待されます。 ただし、アプリケーションをネイティブ実行可能ファイルにコンパイルするときには機能しない可能性があります。 ネイティブ実行可能ファイルをビルドするには、既存の Quarkus JDBC エクステンションを使用するか、ドライバー用の新しいエクステンションを提供します。
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を使用する場合、Hibernateレイヤーは自動的にデータソースを選択し、それを使用します。
データソースへのコード内アクセスは、他のBeanと同様に以下のように取得します:
@Inject
AgroalDataSource defaultDataSource;
上記の例では、型は javax.sql.DataSource
のサブタイプである AgroalDataSource
です。
このため、 javax.sql.DataSource
を注入される型として使用することもできます。
Oracle に関する考慮事項
issue #36265 に記載されているように、 Oracle には、接続終了時にコミットされていないトランザクションをコミットするという非常に奇妙な動作があります。
つまり、たとえば Quarkus を停止する場合、進行中のトランザクションは不完全であってもコミットされる可能性があります。
これは想定された動作ではなく、データ損失につながる可能性があるため、接続終了時に未完了のトランザクションをロールバックするインターセプターを追加しました。 ただし、XA を使用している場合は、トランザクションマネージャーが処理を行うため、このインターセプターは適用されません。
3.18 で導入されたこの動作が特定のワークロードで問題を引き起こす場合は、-Dquarkus-oracle-no-automatic-rollback-on-connection-close
システムプロパティーを true
に設定して無効化できます。
必要に応じてこの動作を調整できるように、https://github.com/quarkusio/quarkus/issues[課題トラッカー] にユースケースを報告してください。
リアクティブデータソース
Quarkusには、リアクティブデータソースで使用できるリアクティブクライアントがいくつかあります。
-
対応するエクステンションをアプリケーションに追加します:
-
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
インストールされているエクステンションは、データソースの設定で定義する
quarkus.datasource.db-kind
と一致している必要があります。
-
-
ドライバーを追加したら、接続URLを設定し、接続プールの適切なサイズを定義します。
quarkus.datasource.reactive.url=postgresql:///your_database quarkus.datasource.reactive.max-size=20
リアクティブ接続プールのサイズ調整
負荷のピーク時の過負荷からデータベースを保護するには、データベースの負荷を軽減するためにプールのサイズを適切に設定します。 適切なサ イ ズは常に、 並列アプ リ ケーシ ョ ンのユーザー数や作業負荷の性質な ど、 さ ま ざ ま な要因に よ っ て異な り ます。
プールサイズを小さく設定しすぎると、接続待ちの間にタイムアウトする リクエストが出てくるかもしれないことに注意してください。
プールサイズ調整プロパティーの詳細は、Reactive データソース設定リファレンス セクションを参照してください。
JDBC とリアクティブデータソースの同時利用
同じデータベースの種類用の JDBC エクステンションとリアクティブデータソースエクステンションが両方とも含まれている場合、デフォルトで JDBC データソースとリアクティブデータソースの両方が作成されます。
JDBC データソースとリアクティブデータソースの両方を作成しない場合は、次の設定を使用します。
-
JDBC データソースを明示的に無効にするには、次のようにします:
quarkus.datasource.jdbc=false
-
リアクティブデータソースを明示的に無効にするには、次のようにします:
quarkus.datasource.reactive=false
ほとんどの場合、JDBC ドライバーまたはリアクティブデータソースエクステンションのどちらかが存在し、両方は存在しないため、上記の構成はオプションになります。
複数のデータソースの設定
Hibernate ORM エクステンションは、設定プロパティーを使用した 永続化ユニット の定義をサポートしています。 各固有化ユニットに対して、任意のデータソースを指定します。 |
複数のデータソースの定義は、単一のデータソースを定義するのと同じように機能しますが、重要な変更点が 1 つあります。それは、各データソースの名前 (設定プロパティー) を指定する必要があることです。
以下の例では、3つの異なるデータソースを提供しています:
-
デフォルトのデータソース
-
users
という名前のデータソース -
inventory
という名前のデータソース
それぞれの設定は次のとおりです。
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]
.
データベースエクステンションが1つしかインストールされていない場合でも、名前付きデータベースをQuarkusで検出できるように、少なくとも1つのビルド時プロパティーを指定する必要があります。
一般的に、これは db-kind プロパティーですが、 Dev Services for Databases のガイドに従って、名前付きデータソースを作成するためにDev Servicesプロパティーを指定することもできます。
|
名前付きデータソース注入
複数のデータソースを使用する場合は、各 DataSource
にデータソース名を値として指定した io.quarkus.agroal.DataSource
修飾子を付与してください。
前のセクションで述べたプロパティーを使用して3つの異なるデータソースを設定し、それぞれのデータソースに以下のように注入します:
@Inject
AgroalDataSource defaultDataSource;
@Inject
@DataSource("users")
AgroalDataSource usersDataSource;
@Inject
@DataSource("inventory")
AgroalDataSource inventoryDataSource;
データソースをアクティブ化または非アクティブ化する
データソースがビルド時で設定され、その URL がランタイムに設定されている場合、デフォルトでアクティブになります。 つまり、アプリケーションの起動時に、Quarkus は対応する JDBC 接続プールまたはリアクティブクライアントを起動します。
ランタイムにデータソースを非アクティブ化するには、次のいずれかを実行します。
-
quarkus.datasource[.optional name].jdbc.url
/quarkus.datasource[.optional name].reactive.url
を設定しないでください。 -
または、
quarkus.datasource[.optional name].active
をfalse
に設定します。
データソースがアクティブでない場合は、以下のようになります。
-
データソースは、アプリケーションの起動中にデータベースへの接続を試行しません。
-
データソースは、health check に貢献しません。
-
データソース (
@Inject DataSource ds
または@Inject Pool pool
) に関連する静的 CDI インジェクションポイントにより、アプリケーションの起動が失敗します。 -
データソースの動的な取得 (例:
CDI.getBeanContainer()
/Arc.instance()
経由またはInstance<DataSource>
の注入による) を実行すると、例外がスローされます。 -
データソースを使用する他の Quarkusエクステンションにより、アプリケーションの起動が失敗する可能性があります。
このような場合は、他のエクステンションも無効にする必要があります。 このシナリオの例については、「Hibernate ORM ガイド」の こちらのセクション を参照してください。
この機能は、実行時にアプリケーションが定義済みのセットから 1 つのデータソースを選択する必要がある場合に特に便利です。
例えば、次のような設定です:
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
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.
カスタム設定プロファイル を使用すると、このようなセットアップを簡素化できます。
上記の設定に以下のプロファイル固有の設定を追加することで、
|
このようなセットアップでは、アクティブな データソースにのみアクセスするように注意する必要があります。
そのためには、@Any
修飾子を使用して InjectableInstance<DataSource>
または InjectableInstance<Pool>
を注入し、getActive()
を呼び出します。
import io.quarkus.arc.InjectableInstance;
@ApplicationScoped
public class MyConsumer {
@Inject
@Any
InjectableInstance<DataSource> dataSource;
public void doSomething() {
DataSource activeDataSource = dataSource.getActive();
// ...
}
}
または、次のように、現在アクティブな名前付きデータソースにリダイレクトするデフォルトのデータソースの CDI Bean プロデューサー を定義して、直接注入できるようにすることもできます。
public class MyProducer {
@Inject
@DataSource("pg")
InjectableInstance<DataSource> pgDataSourceBean; (1)
@Inject
@DataSource("oracle")
InjectableInstance<DataSource> oracleDataSourceBean;
@Produces (2)
@ApplicationScoped
public DataSource dataSource() {
if (pgDataSourceBean.getHandle().getBean().isActive()) { (3)
return pgDataSourceBean.get();
} else if (oracleDataSourceBean.getHandle().getBean().isActive()) { (3)
return oracleDataSourceBean.get();
} else {
throw new RuntimeException("No active datasource!");
}
}
}
@ApplicationScoped
public class MyConsumer {
@Inject
DataSource dataSource; (4)
public void doSomething() {
// .. just use the injected datasource ...
}
}
1 | DataSource または AgroalDatasource を直接注入しないでください。
起動時に失敗する可能性があるためです (非アクティブな Bean を注入できません)。
代わりに、InjectableInstance<DataSource> または InjectableInstance<AgroalDataSource> を注入します。 |
2 | CDI プロデューサーメソッドを宣言し、アクティブなものに応じてデフォルトのデータソース を PostgreSQL または Oracle として定義します。 |
3 | Bean を取得する前に、Bean がアクティブか確認します。 |
4 | これには、(唯一の) アクティブなデータソースが注入されます。 |
単一のトランザクションで複数のデータソースを使用する
デフォルトでは、データソースでの XA サポートは無効になっています。 したがって、トランザクションには 1 つのデータソースしか含めることができません。 同じトランザクションで複数の非 XA データソースにアクセスしようとすると、次のような例外が発生します。
...
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 データソースを使用できるようにするには、次の手順を実行します。
-
JDBC ドライバーが XA をサポートしていることを確認してください。 すべての supported JDBC drivers do サポート対象の JDBC ドライバーはサポートしていますが、other JDBC drivers 他の JDBC ドライバーはサポートしていない場合があります。
-
データベースサーバーが XA を有効化するように設定されていることを確認します。
-
Enable XA support explicitly for each relevant datasource by setting
quarkus.datasource[.optional name].jdbc.transactions
toxa
.
XA を使用すると、1 つのデータソースでのロールバックにより、トランザクションに登録されている他のすべてのデータソースでのロールバックがトリガーされます。
現時点では、リアクティブデータソース上の XA トランザクションはサポートされていません。 |
トランザクションにデータソース以外のリソースが含まれる場合は、そのリソースで XA トランザクションがサポートされていない可能性や、追加の設定が必要になる可能性があることに注意してください。 |
1 つのデータソースに対して XA を有効にできない場合:
-
1 つだけを除く すべてのデータソースに対して XA を有効にすることは、Last Resource Commit Optimization (LRCO) を通じて引き続きサポートされている点に注意してください。
-
1 つのデータソースのロールバックによって他のデータソースのロールバックをトリガーする必要がない場合は、コードを複数のトランザクションに分割することを検討してください。 これを行うには、
QuarkusTransaction.requiringNew()
/@Transactional(REQUIRES_NEW)
(推奨) またはUserTransaction
(より複雑なユースケースの場合) を使用します。
他の解決策が機能しない場合や、Quarkus 3.8 以前との互換性を維持するには、 このプロパティーを allow に設定すると、トランザクションロールバックが最後の非 XA データソースにのみ適用されます。一方、他の非 XA データソースがすでに変更をコミットしている場合、システム全体が不整合な状態になる可能性があります。 または、そのような安全でない動作を許可し、その動作が有効になったときに警告を記録することもできます。
この設定プロパティーの使用は推奨されません。将来的には削除される予定なので、それに応じてアプリケーションを修正する必要があります。 この機能のユースケースが有効であり、このオプションを維持すべきだと思われる場合は、Quarkus トラッカー で issue を作成し、 理由を説明してください。 |
データソースの統合
データソースのヘルスチェック
quarkus-smallrye-health エクステンションを使用する場合、 quarkus-agroal
およびリアクティブクライアントエクステンションは、 データソースを検証するためのreadiness ヘルスチェックを自動的に追加します。
アプリケーションのヘルスチェックエンドポイント /q/health/ready
(デフォルト) にアクセスすると、データソースの検証状況に関する情報を受け取ります。
複数のデータソースがある場合は、すべてのデータソースがチェックされ、データソースの検証に失敗した場合は、ステータスが DOWN
に変わります。
この動作を無効にするには、 quarkus.datasource.health.enabled
プロパティーを使用します。
特定のデータソースのみをヘルスチェックから除外するには、以下を使用します。
quarkus.datasource."datasource-name".health-exclude=true
データソースのメトリクス
quarkus-micrometer または quarkus-smallrye-metrics エクステンションを使用している場合、quarkus-agroal
は、データソース関連のメトリクスをメトリクスレジストリーに貢献できます。
これは、quarkus.datasource.metrics.enabled
プロパティーを true
に設定することで有効になります。
公開されたメトリクスが実際の値を含むためには、Agroal メカニズムによって内部的にメトリクス収集が有効になっている必要があります。 デフォルトでは、メトリクスエクステンションが存在し、Agroal エクステンションのメトリクスが有効になっている場合、このメトリクス収集メカニズムはすべてのデータソースに対して有効になります。
特定のデータソースのメトリクスを無効にするには、quarkus.datasource.jdbc.enable-metrics
を false
に設定するか、名前付きデータソースに対して quarkus.datasource.<datasource name>.jdbc.enable-metrics
を適用します。
これにより、メトリクスを収集するメカニズムが無効になっている場合は、メトリクスを収集して /q/metrics
エンドポイントで公開することが無効になります。
逆に、quarkus.datasource.jdbc.enable-metrics
を true
に設定するか、 quarkus.datasource.<datasource name>.jdbc.enable-metrics
を名前付きデータソースに設定すると、メトリクスエクステンションが使用されていない場合でも、メトリクスコレクションを明示的に有効にします。
これは、収集されたメトリクスにプログラムでアクセスする必要がある場合に役立ちます。
これらは、注入された AgroalDataSource
インスタンスで dataSource.getMetrics()
を呼び出した後に使用可能になります。
このデータソースのメトリクス収集が無効な場合は、すべての値がゼロになります。
データソースのトレース
データソースでトレースを使用するには、プロジェクトに quarkus-opentelemetry
エクステンションを追加する必要があります。
トレーシングを有効化するために別のドライバーを宣言する必要はありません。 JDBC ドライバーを使用する場合は、OpenTelemetry エクステンションの手順 に従う必要があります。
すべてのトレースインフラストラクチャーが整っていても、データソーストレースはデフォルトでは有効になっていません。そのため、次のプロパティーを設定して有効にする必要があります。
# enable tracing
quarkus.datasource.jdbc.telemetry=true
Narayanaトランザクションマネージャの統合
Narayana JTAエクステンションも利用可能であれば、統合は自動的に行われます。
transactions
設定プロパティーを設定することで、これをオーバーライドできます。
-
quarkus.datasource.jdbc.transactions
(デフォルトの無名データソースの場合) -
quarkus.datasource.<datasource-name>.jdbc.transactions
(名前付きデータソースの場合)
詳細は、以下の Configuration reference セクションを参照してください。
jdbcを使用してトランザクションログをデータベースに保存しやすくするには、 Quarkusのトランザクションの使用 ガイドの トランザクションログをデータソースに保存するように設定する セクションを参照してください。
インメモリーデータベースを使用したテスト
H2やDerbyのようないくつかのデータベースは、結合テストを迅速に実行するための機能として、 組み込み モードで一般的に使用されています。
特に、dev Services がテスト用のゼロコンフィグデータベースを提供して おり、コンテナーに対してテストを実行すると比較的短時間で実際の環境で期待通りの結果が得られる場合は、本番環境で使用する予定の実際のデータベースを使用することをお勧めします。 しかし、単純な統合テストを実行する機能が必要なシナリオでは、JVM で動作するデータベースを使用することも可能です。
サポートと制限
組み込みデータベース(H2およびDerby)はJVMモードで動作します。 ネイティブモードでは、以下の制限が適用されます:
-
Derbyをネイティブモードでアプリケーションに組み込むことはできません。 しかし、Quarkus Derbyエクステンションを使用すると、Derby JDBC クライアント をネイティブにコンパイルして、 リモート 接続をサポートできます。
-
ネイティブイメージにH2を埋め込むことは推奨されません。 例えば、別のデータベースへのリモート接続を使用するなど、別の方法を検討してください。
統合テストの実行
-
次の Maven コーディネートの下にある追加ツールを提供するアーティファクトに依存関係を追加します。
-
io.quarkus:quarkus-test-h2
H2の場合 -
io.quarkus:quarkus-test-derby
ダービーの場合これにより、アプリケーションをネイティブの実行可能ファイルにコンパイルしても、データベースはJVMプロセスとして実行されます。
-
-
JVM とネイティブの実行可能ファイルの両方で統合テストを実行するために、結合テストの任意のクラスに以下の特定のアノテーションを追加します:
-
@QuarkusTestResource(H2DatabaseTestResource.class)
-
@QuarkusTestResource(DerbyDatabaseTestResource.class)
これにより、テストスイートは、テスト実行に必要な別プロセスで管理データベースを起動し、終了します。
H2の例package my.app.integrationtests.db; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.h2.H2DatabaseTestResource; @QuarkusTestResource(H2DatabaseTestResource.class) public class TestResources { }
-
-
マネージドデータベースへの接続を設定します:
quarkus.datasource.db-kind=h2 quarkus.datasource.jdbc.url=jdbc:h2:tcp://localhost/mem:test
参照
共通データソース設定リファレンス
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべてランタイム時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
||
---|---|---|---|---|
Whether or not a health check is published in case the smallrye-health extension is present. This is a global setting and is not specific to a datasource. Environment variable: Show more |
boolean |
|
||
Whether or not datasource metrics are published in case a metrics extension is present. This is a global setting and is not specific to a datasource.
Environment variable: Show more |
boolean |
|
||
The kind of database we will connect to (e.g. h2, postgresql…). Environment variable: Show more |
string |
|||
The version of the database we will connect to (e.g. '10.0').
As a rule, the version set here should be as high as possible, but must be lower than or equal to the version of any database your application will connect to. A high version will allow better performance and using more features (e.g. Hibernate ORM may generate more efficient SQL, avoid workarounds and take advantage of more database features), but if it is higher than the version of the database you want to connect to, it may lead to runtime exceptions (e.g. Hibernate ORM may generate invalid SQL that your database will reject). Some extensions (like the Hibernate ORM extension) will try to check this version against the actual database version on startup, leading to a startup failure when the actual version is lower or simply a warning in case the database cannot be reached. The default for this property is specific to each extension; the Hibernate ORM extension will default to the oldest version it supports. Environment variable: Show more |
string |
|||
Whether this particular data source should be excluded from the health check if the general health check for data sources is enabled. By default, the health check includes all configured data sources (if it is enabled). Environment variable: Show more |
boolean |
|
||
Whether this datasource should be active at runtime. Environment variable: Show more |
boolean |
|
||
The datasource username Environment variable: Show more |
string |
|||
The datasource password Environment variable: Show more |
string |
|||
The credentials provider name Environment variable: Show more |
string |
|||
The credentials provider bean name. This is a bean name (as in For Vault, the credentials provider bean name is Environment variable: Show more |
string |
|||
型 |
デフォルト |
|||
Whether this Dev Service should start with the application in dev mode or tests. Dev Services are enabled by default unless connection configuration (e.g. the JDBC URL or reactive client URL) is set explicitly. Environment variable: Show more |
boolean |
|||
The container image name for container-based Dev Service providers. This has no effect if the provider is not a container-based database, such as H2 or Derby. Environment variable: Show more |
string |
|||
Environment variables that are passed to the container. Environment variable: Show more |
Map<String,String> |
|||
Generic properties that are passed for additional container configuration. Properties defined here are database-specific and are interpreted specifically in each database dev service implementation. Environment variable: Show more |
Map<String,String> |
|||
Generic properties that are added to the database connection URL. Environment variable: Show more |
Map<String,String> |
|||
Optional fixed port the dev service will listen to. If not defined, the port will be chosen randomly. Environment variable: Show more |
int |
|||
The container start command to use for container-based Dev Service providers. This has no effect if the provider is not a container-based database, such as H2 or Derby. Environment variable: Show more |
string |
|||
The database name to use if this Dev Service supports overriding it. Environment variable: Show more |
string |
|||
The username to use if this Dev Service supports overriding it. Environment variable: Show more |
string |
|||
The password to use if this Dev Service supports overriding it. Environment variable: Show more |
string |
|||
The paths to SQL scripts to be loaded from the classpath and applied to the Dev Service database. This has no effect if the provider is not a container-based database, such as H2 or Derby. Environment variable: Show more |
list of string |
|||
The volumes to be mapped to the container. The map key corresponds to the host location; the map value is the container location. If the host location starts with "classpath:", the mapping loads the resource from the classpath with read-only permission. When using a file system location, the volume will be generated with read-write permission, potentially leading to data loss or modification in your file system. This has no effect if the provider is not a container-based database, such as H2 or Derby. Environment variable: Show more |
Map<String,String> |
|||
Whether to keep Dev Service containers running after a dev mode session or test suite execution to reuse them in the next dev mode session or test suite execution. Within a dev mode session or test suite execution, Quarkus will always reuse Dev Services as long as their configuration (username, password, environment, port bindings, …) did not change. This feature is specifically about keeping containers running when Quarkus is not running to reuse them across runs.
This configuration property is set to Environment variable: Show more |
boolean |
|
||
Whether the logs should be consumed by the JBoss logger. This has no effect if the provider is not a container-based database, such as H2 or Derby. Environment variable: Show more |
boolean |
|
JDBC 設定リファレンス
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべてランタイム時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
---|---|---|
Activate or disable the dev ui page. Environment variable: Show more |
boolean |
|
Allow sql queries in the Dev UI page Environment variable: Show more |
boolean |
|
Append this to the select done to fetch the table values. eg: LIMIT 100 or TOP 100 Environment variable: Show more |
string |
|
Allowed database host. By default only localhost is allowed. Any provided host here will also be allowed Environment variable: Show more |
string |
|
If we create a JDBC datasource for this datasource. Environment variable: Show more |
boolean |
|
The datasource driver class name Environment variable: Show more |
string |
|
Whether we want to use regular JDBC transactions, XA, or disable all transactional capabilities. When enabling XA you will need a driver implementing Environment variable: Show more |
|
|
Enable datasource metrics collection. If unspecified, collecting metrics will be enabled by default if a metrics extension is active. Environment variable: Show more |
boolean |
|
Enable OpenTelemetry JDBC instrumentation. Environment variable: Show more |
boolean |
|
The datasource URL Environment variable: Show more |
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. Environment variable: Show more |
int |
|
The datasource pool minimum size Environment variable: Show more |
int |
|
The datasource pool maximum size Environment variable: Show more |
int |
|
The interval at which we validate idle connections in the background. Set to Environment variable: Show more |
|
|
Perform foreground validation on connections that have been idle for longer than the specified interval. Environment variable: Show more |
||
The timeout before cancelling the acquisition of a new connection Environment variable: Show more |
|
|
The interval at which we check for connection leaks. Environment variable: Show more |
|
|
The interval at which we try to remove idle connections. Environment variable: Show more |
|
|
The max lifetime of a connection. Environment variable: Show more |
|
|
The transaction isolation level. Environment variable: Show more |
|
|
Collect and display extra troubleshooting info on leaked connections. Environment variable: Show more |
boolean |
|
Allows connections to be flushed upon return to the pool. It’s not enabled by default. Environment variable: Show more |
boolean |
|
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. Environment variable: Show more |
boolean |
|
Query executed when first using a connection. Environment variable: Show more |
string |
|
Query executed to validate a connection. Environment variable: Show more |
string |
|
Forces connection validation prior to acquisition (foreground validation) regardless of the idle status. Because of the overhead of performing validation on every call, it’s recommended to rely on default idle validation instead, and to leave this to Environment variable: Show more |
boolean |
|
Disable pooling to prevent reuse of Connections. Use this when an external pool manages the life-cycle of Connections. Environment variable: Show more |
boolean |
|
Require an active transaction when acquiring a connection. Recommended for production. WARNING: Some extensions acquire connections without holding a transaction for things like schema updates and schema validation. Setting this setting to STRICT may lead to failures in those cases. Environment variable: Show more |
|
|
Other unspecified properties to be passed to the JDBC driver when creating new connections. Environment variable: Show more |
Map<String,String> |
|
Enable OpenTelemetry JDBC instrumentation. Environment variable: Show more |
boolean |
|
期間フォーマットについて
To write duration values, use the standard 数字で始まる簡略化した書式を使うこともできます:
その他の場合は、簡略化されたフォーマットが解析のために
|
JDBC URL リファレンス
サポートされているデータベースには、それぞれ異なる JDBC URL 設定オプションがあります。 以下のセクションでは、各データベース URL の概要と公式ドキュメントへのリンクを示しています。
DB2
jdbc:db2://<serverName>[:<portNumber>]/<databaseName>[:<key1>=<value>;[<key2>=<value2>;]]
- 例
-
jdbc:db2://localhost:50000/MYDB:user=dbadm;password=dbadm;
URL構文と追加のサポートされるオプションの詳細については、 公式ドキュメント を参照してください。
Derby
jdbc:derby:[//serverName[:portNumber]/][memory:]databaseName[;property=value[;property=value]]
- 例
-
jdbc:derby://localhost:1527/myDB
,jdbc:derby:memory:myDB;create=true
Derbyは組み込みデータベースであり、サーバーとして実行することも、ファイルに基づいて実行することも、完全にメモリー内で実行することもできます。 上記のオプションはすべて利用可能です。
詳しくは 公式ドキュメント をご覧ください。
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は、組み込みモードでもサーバーモードでも動作するデータベースです。 ファイルストレージを使用することも、完全にメモリ内で実行することもできます。 これらのオプションはすべて、上記のように利用可能です。
詳しくは 公式ドキュメント をご覧ください。
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
詳しくは 公式ドキュメント をご覧ください。
Microsoft SQL server
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
- 例
-
jdbc:sqlserver://localhost:1433;databaseName=AdventureWorks
Microsoft SQL Server JDBC ドライバーは、基本的に他のドライバーと同じように動作します。
詳しくは 公式ドキュメント をご覧ください。
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
詳しくは 公式ドキュメント をご覧ください。
Oracle
jdbc:oracle:driver_type:@database_specifier
- 例
-
jdbc:oracle:thin:@localhost:1521/ORCL_SVC
詳しくは 公式ドキュメント をご覧ください。
PostgreSQL
jdbc:postgresql:[//][host][:port][/database][?key=value…]
- 例
-
jdbc:postgresql://localhost/test
各パートのデフォルトは以下の通り:
host
-
localhost
port
-
5432
database
-
ユーザー名と同じ名前
追加パラメーターの詳細は、公式ドキュメント を参照してください。
Quarkusエクステンションとデータベースドライバーのリファレンス
次の表には、組み込みの db-kind
値、対応する Quarkus エクステンション、およびそれらのエクステンションで使用される JDBC ドライバーが記載されています。
ビルトインデータソースの種類のいずれかを使用する場合、JDBC ドライバーとリアクティブドライバーはこの表の値と一致するように自動的に解決されます。
データベースの種類 | Quarkusエクステンション | Drivers |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
データベースの種類 | Quarkusエクステンション | ドライバー |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
この自動解決はほとんどの場合に適用可能であり、ドライバーの設定は必要ありません。 |
Reactive データソース設定リファレンス
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべてランタイム時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
---|---|---|
If we create a Reactive datasource for this datasource. Environment variable: Show more |
boolean |
|
Whether prepared statements should be cached on the client side. Environment variable: Show more |
boolean |
|
The datasource URLs. If multiple values are set, this datasource will create a pool with a list of servers instead of a single server. The pool uses round-robin load balancing for server selection during connection establishment. Note that certain drivers might not accommodate multiple values in this context. Environment variable: Show more |
list of string |
|
The datasource pool maximum size. Environment variable: Show more |
int |
|
When a new connection object is created, the pool assigns it an event loop. When Environment variable: Show more |
int |
|
Whether all server certificates should be trusted. Environment variable: Show more |
boolean |
|
PEM Trust config is disabled by default. Environment variable: Show more |
boolean |
|
Comma-separated list of the trust certificate files (Pem format). Environment variable: Show more |
list of string |
|
JKS config is disabled by default. Environment variable: Show more |
boolean |
|
Path of the key file (JKS format). Environment variable: Show more |
string |
|
Password of the key file. Environment variable: Show more |
string |
|
PFX config is disabled by default. Environment variable: Show more |
boolean |
|
Path to the key file (PFX format). Environment variable: Show more |
string |
|
Password of the key. Environment variable: Show more |
string |
|
PEM Key/cert config is disabled by default. Environment variable: Show more |
boolean |
|
Comma-separated list of the path to the key files (Pem format). Environment variable: Show more |
list of string |
|
Comma-separated list of the path to the certificate files (Pem format). Environment variable: Show more |
list of string |
|
JKS config is disabled by default. Environment variable: Show more |
boolean |
|
Path of the key file (JKS format). Environment variable: Show more |
string |
|
Password of the key file. Environment variable: Show more |
string |
|
PFX config is disabled by default. Environment variable: Show more |
boolean |
|
Path to the key file (PFX format). Environment variable: Show more |
string |
|
Password of the key. Environment variable: Show more |
string |
|
The number of reconnection attempts when a pooled connection cannot be established on first try. Environment variable: Show more |
int |
|
The interval between reconnection attempts when a pooled connection cannot be established on first try. Environment variable: Show more |
|
|
The hostname verification algorithm to use in case the server’s identity should be checked. Should be Environment variable: Show more |
string |
|
The maximum time a connection remains unused in the pool before it is closed. Environment variable: Show more |
|
|
The maximum time a connection remains in the pool, after which it will be closed upon return and replaced as necessary. Environment variable: Show more |
|
|
Set to true to share the pool among datasources. There can be multiple shared pools distinguished by name, when no specific name is set, the Environment variable: Show more |
boolean |
|
Set the pool name, used when the pool is shared among datasources, otherwise ignored. Environment variable: Show more |
string |
|
Other unspecified properties to be passed through the Reactive SQL Client directly to the database when new connections are initiated. Environment variable: Show more |
Map<String,String> |
期間フォーマットについて
To write duration values, use the standard 数字で始まる簡略化した書式を使うこともできます:
その他の場合は、簡略化されたフォーマットが解析のために
|
Reactive DB2 設定
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべてランタイム時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
---|---|---|
型 |
デフォルト |
|
Whether SSL/TLS is enabled. Environment variable: Show more |
boolean |
|
Reactive MariaDB/MySQL固有の設定
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべてランタイム時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
---|---|---|
型 |
デフォルト |
|
Charset for connections. Environment variable: Show more |
string |
|
Collation for connections. Environment variable: Show more |
string |
|
Desired security state of the connection to the server. Environment variable: Show more |
|
|
Connection timeout in seconds Environment variable: Show more |
int |
|
The authentication plugin the client should use. By default, it uses the plugin name specified by the server in the initial handshake packet. Environment variable: Show more |
|
|
The maximum number of inflight database commands that can be pipelined. By default, pipelining is disabled. Environment variable: Show more |
int |
|
Whether to return the number of rows matched by the WHERE clause in UPDATE statements, instead of the number of rows actually changed. Environment variable: Show more |
ブーリアン |
|
Reactive Microsoft SQLサーバー固有の設定
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべてランタイム時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
---|---|---|
型 |
デフォルト |
|
The desired size (in bytes) for TDS packets. Environment variable: Show more |
int |
|
Whether SSL/TLS is enabled. Environment variable: Show more |
boolean |
|
Reactive Oracle固有の設定
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべてランタイム時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
---|---|---|
No configuration properties found. |
Reactive PostgreSQL固有の設定
ビルド時に固定された設定プロパティー。その他の設定プロパティーはすべてランタイム時にオーバーライド可能です。
Configuration property |
型 |
デフォルト |
---|---|---|
型 |
デフォルト |
|
The maximum number of inflight database commands that can be pipelined. Environment variable: Show more |
int |
|
SSL operating mode of the client. Environment variable: Show more |
|
|
Level 7 proxies can load balance queries on several connections to the actual database. When it happens, the client can be confused by the lack of session affinity and unwanted errors can happen like ERROR: unnamed prepared statement does not exist (26000). See Using a level 7 proxy Environment variable: Show more |
boolean |
|
Reactive データソースの URL 参照
DB2
db2://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
- 例
-
db2://dbuser:secretpassword@database.server.com:50000/mydb
現在、クライアントは以下のパラメーターキーをサポートしています。
-
host
-
port
-
user
-
password
-
database
接続 URL でパラメーターを設定すると、デフォルトのプロパティーが上書きされます。 |
Microsoft SQL server
sqlserver://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
- 例
-
sqlserver://dbuser:secretpassword@database.server.com:1433/mydb
現在、クライアントは以下のパラメーターキーをサポートしています。
-
host
-
port
-
user
-
password
-
database
接続 URL でパラメーターを設定すると、デフォルトのプロパティーが上書きされます。 |
MySQL / MariaDB
mysql://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
- 例
-
mysql://dbuser:secretpassword@database.server.com:3211/mydb
現在、クライアントは以下のパラメーターキーをサポートしています (大文字と小文字を区別します)。
-
host
-
port
-
user
-
password
-
schema
-
socket
-
useAffectedRows
接続 URL でパラメーターを設定すると、デフォルトのプロパティーが上書きされます。 |
Oracle
PostgreSQL
postgresql://[user[:[password]]@]host[:port][/database][?<key1>=<value1>[&<key2>=<value2>]]
- 例
-
postgresql://dbuser:secretpassword@database.server.com:5432/mydb
現在、クライアントは以下をサポートしています:
-
以下のパラメーターキー:
-
host
-
port
-
user
-
password
-
dbname
-
sslmode
-
-
次のような追加のプロパティー:
-
application_name
-
fallback_application_name
-
search_path
-
options
-
接続 URL でパラメーターを設定すると、デフォルトのプロパティーが上書きされます。 |