The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

MongoDB クライアントの利用

MongoDBは広く使われているNoSQLデータベースとして知られています。

このガイドでは、RESTサービスでMongoDBデータベースを使用する方法を見ていきます。

前提条件

このガイドを完成させるには、以下が必要です:

  • 約15分

  • IDE

  • JDK 17+がインストールされ、 JAVA_HOME が適切に設定されていること

  • Apache Maven 3.9.6

  • 使用したい場合は、 Quarkus CLI

  • ネイティブ実行可能ファイルをビルドしたい場合、MandrelまたはGraalVM(あるいはネイティブなコンテナビルドを使用する場合はDocker)をインストールし、 適切に設定していること

  • MongoDBがインストールされているか、Dockerがインストールされている

アーキテクチャ

このガイドで構築されるアプリケーションは非常にシンプルです: ユーザーはフォームを使用してリストに要素を追加することができ、リストは更新されます。

ブラウザとサーバー間の情報はすべてJSON形式になっています。

要素はMongoDBに格納されています。

ソリューション

次の章で紹介する手順に沿って、ステップを踏んでアプリを作成することをお勧めします。ただし、完成した例にそのまま進んでも構いません。

Gitレポジトリをクローンするか git clone https://github.com/quarkusio/quarkus-quickstarts.gitアーカイブ をダウンロードします。

ソリューションは mongodb-quickstart ディレクトリ にあります。

Mavenプロジェクトの作成

まず、新しいプロジェクトが必要です。以下のコマンドで新規プロジェクトを作成します。

コマンドラインインタフェース
quarkus create app org.acme:mongodb-quickstart \
    --extension='resteasy-reactive-jackson,mongodb-client' \
    --no-code
cd mongodb-quickstart

Gradleプロジェクトを作成するには、 --gradle または --gradle-kotlin-dsl オプションを追加します。

Quarkus CLIのインストールと使用方法の詳細については、 Quarkus CLI ガイドを参照してください。

Maven
mvn io.quarkus.platform:quarkus-maven-plugin:3.8.3:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=mongodb-quickstart \
    -Dextensions='resteasy-reactive-jackson,mongodb-client' \
    -DnoCode
cd mongodb-quickstart

Gradleプロジェクトを作成するには、 -DbuildTool=gradle または -DbuildTool=gradle-kotlin-dsl オプションを追加します。

Windowsユーザーの場合:

  • cmdを使用する場合、(バックスラッシュ \ を使用せず、すべてを同じ行に書かないでください)。

  • Powershellを使用する場合は、 -D パラメータを二重引用符で囲んでください。例: "-DprojectArtifactId=mongodb-quickstart"

このコマンドは、RESTEasy Reactive JacksonとMongoDB ClientエクステンションをインポートするMaven構造を生成します。その後、 quarkus-mongodb-client エクステンションがビルドファイルに追加されます。

すでにQuarkusプロジェクトが設定されている場合は、プロジェクトのベースディレクトリーで以下のコマンドを実行することで、プロジェクトに mongodb-client エクステンションを追加することができます。

コマンドラインインタフェース
quarkus extension add mongodb-client
Maven
./mvnw quarkus:add-extension -Dextensions='mongodb-client'
Gradle
./gradlew addExtension --extensions='mongodb-client'

これにより、 pom.xml に以下が追加されます:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-mongodb-client</artifactId>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-mongodb-client")

初めてのJSON RESTサービスの作成

この例では、果物のリストを管理するアプリケーションを作成します。

まず、以下のように Fruit Bean を作成してみましょう。

package org.acme.mongodb;

import java.util.Objects;

public class Fruit {

    private String name;
    private String description;
    private String id;

    public Fruit() {
    }

    public Fruit(String name, String description) {
        this.name = name;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Fruit)) {
            return false;
        }

        Fruit other = (Fruit) obj;

        return Objects.equals(other.name, this.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.name);
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }
}

派手なことは何もありません。注意すべき重要なことは、デフォルトのコンストラクタを持つことはJSONシリアライズレイヤーで必須であるということです。

今、私たちのアプリケーションのビジネス層となる org.acme.mongodb.FruitService を作成し、mongoDB データベースからフルーツを保存/ロードします。

package org.acme.mongodb;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.bson.Document;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@ApplicationScoped
public class FruitService {

    @Inject MongoClient mongoClient;

    public List<Fruit> list(){
        List<Fruit> list = new ArrayList<>();
        MongoCursor<Document> cursor = getCollection().find().iterator();

        try {
            while (cursor.hasNext()) {
                Document document = cursor.next();
                Fruit fruit = new Fruit();
                fruit.setName(document.getString("name"));
                fruit.setDescription(document.getString("description"));
                list.add(fruit);
            }
        } finally {
            cursor.close();
        }
        return list;
    }

    public void add(Fruit fruit){
        Document document = new Document()
                .append("name", fruit.getName())
                .append("description", fruit.getDescription());
        getCollection().insertOne(document);
    }

    private MongoCollection getCollection(){
        return mongoClient.getDatabase("fruit").getCollection("fruit");
    }
}

では、次のように org.acme.mongodb.FruitResource クラスを作成します。

@Path("/fruits")
public class FruitResource {

    @Inject FruitService fruitService;

    @GET
    public List<Fruit> list() {
        return fruitService.list();
    }

    @POST
    public List<Fruit> add(Fruit fruit) {
        fruitService.add(fruit);
        return list();
    }
}

実装は非常に簡単で、Jakarta RESTアノテーションを使ってエンドポイントを定義し、 FruitService を使って新しい果物をリストアップ/追加するだけです。

MongoDBデータベースの設定

設定する主なプロパティーはMongoDBにアクセスするためのURLです。ほとんどすべての設定は接続URIに含めることができるので、そうすることをお勧めします。 MongoDBドキュメントで、さらに情報を得ることができます: https://docs.mongodb.com/manual/reference/connection-string/

設定のサンプルは以下のようになります。

# configure the mongoDB client for a replica set of two nodes
quarkus.mongodb.connection-string = mongodb://mongo1:27017,mongo2:27017

この例では、ローカルホスト上で実行されている単一のインスタンスを使用しています。

# configure the mongoDB client for a single instance on localhost
quarkus.mongodb.connection-string = mongodb://localhost:27017

その他の設定プロパティーが必要な場合は、このガイドの最後に完全なリストがあります。

デフォルトでは、Quarkusはアプリケーション内でのJNDIの使用を制限します。これは、log4shellのような将来的な脆弱性を軽減するための予防策です。MongoDBへの接続によく使われる mongo+srv プロトコルはJNDIを必要とするため、MongoDBクライアントエクステンションを使用すると、この保護機能は自動的に無効になります。

開発サービス(コンフィグレーション・フリー・データベース)

QuarkusはDev Servicesと呼ばれる機能をサポートしており、設定なしで様々なデータソースを作成することができます。MongoDBの場合、このサポートはデフォルトのMongoDB接続にまで及びます。実際どう動くかというと、 quarkus.mongodb.connection-string を設定していない場合、Quarkusはテストやdev-modeの実行時に自動的にMongoDBコンテナを起動し、接続を自動的に設定します。

MongoDB Dev Servicesは Testcontainers MongoDBモジュール をベースにしており、単一ノードのレプリカセットを起動することができます。

本番環境のアプリケーションを実行する場合、MongoDBの接続は通常通りに設定する必要があります。本番環境のデータベースの設定を application.properties に含めてDev Servicesを継続して使用する場合は、 %prod. プロファイルを使用してMongoDBの設定を定義することをお勧めします。

ビルド時に固定される設定プロパティ - その他の設定プロパティは実行時にオーバーライド可能です。

Configuration property

デフォルト

If DevServices has been explicitly enabled or disabled. DevServices is generally enabled by default, unless there is an existing configuration present. When DevServices is enabled Quarkus will attempt to automatically configure and start a database when running in Dev or Test mode.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_ENABLED

Show more

boolean

The container image name to use, for container based DevServices providers.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_IMAGE_NAME

Show more

string

Optional fixed port the dev service will listen to.

If not defined, the port will be chosen randomly.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_PORT

Show more

int

Generic properties that are added to the connection URL.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_PROPERTIES

Show more

Map<String,String>

Environment variables that are passed to the container.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_CONTAINER_ENV

Show more

Map<String,String>

複数のMongoDBクライアント

MongoDBでは、複数のクライアントを設定することができます。複数のクライアントを使っても、単一のクライアントを持つのと同じように動作します。

quarkus.mongodb.connection-string = mongodb://login:pass@mongo1:27017/database

quarkus.mongodb.users.connection-string = mongodb://mongo2:27017/userdb
quarkus.mongodb.inventory.connection-string = mongodb://mongo3:27017/invdb,mongo4:27017/invdb

キーに余分なビットがあることに注意してください ( usersinventory のセグメント)。構文は以下の通りです。 quarkus.mongodb.[optional name.][mongo connection property] .名前を省略すると、デフォルトのクライアントを設定します。

複数の MongoDB クライアントを使うことで、複数の MongoDB クラスターに接続できるようになり、MongoDB のマルチテナンシーが可能になります。+ 同じクラスター内の複数のデータベースに接続したい場合は、(JDBC接続が同じデータベース内の複数のスキーマにアクセスできるように) 1つのクライアントで同じクラスター内のすべてのデータベースにアクセスできるので、複数のクライアントは必要あり ません

名前付きMongoクライアントの注入

複数のクライアントを使用する場合、各 MongoClient は、 io.quarkus.mongodb.MongoClientName の修飾子を使用して注入するクライアントを選択できます。上記のプロパティーを使用して、以下のように3つの異なるクライアントを設定し、それぞれに注入することもできます。

@Inject
MongoClient defaultMongoClient;

@Inject
@MongoClientName("users")
MongoClient mongoClient1;

@Inject
@MongoClientName("inventory")
ReactiveMongoClient mongoClient2;

MongoDB データベースの実行

デフォルトでは、 MongoClient はポート 27017 (デフォルトの MongoDB ポート) でローカルの MongoDB データベースにアクセスするように設定されています。このポートで実行されているローカルのデータベースがある場合は、他に何もする必要はありません!

Dockerを使ってMongoDBデータベースを起動したい場合は、以下のコマンドで起動することができます。

docker run -ti --rm -p 27017:27017 mongo:4.4

If you use Dev Services, launching the container manually is not necessary.

フロントエンドの作成

それでは、 FruitResource と対話するための簡単なWebページを追加してみましょう。 Quarkusは自動的に、 META-INF/resources ディレクトリの下にある静的リソースを提供します。 src/main/resources/META-INF/resources ディレクトリに、この fruits.html ファイルのコンテンツを含む fruits.html ファイルを追加します。

これで、REST サービスと対話できるようになりました。

  • Quarkusを起動します。

    コマンドラインインタフェース
    quarkus dev
    Maven
    ./mvnw quarkus:dev
    Gradle
    ./gradlew --console=plain quarkusDev
  • http://localhost:8080/fruits.html をブラウザで開く

  • フォームを使って新しいフルーツをリストに追加します。

リアクティブな MongoDB クライアント

リアクティブなMongoDBクライアントがQuarkusに含まれています。これを使うのは、古典的なMongoDBクライアントを使うのと同じくらい簡単です。先ほどの例を以下のように書き換えて使うことができます。

Mutiny

MongoDBのリアクティブ・クライアントは、Mutinyのリアクティブ・タイプを使用しています。Mutinyに慣れていない方は、 Mutiny - an intuitive reactive programming libraryをご覧ください。

package org.acme.mongodb;

import io.quarkus.mongodb.reactive.ReactiveMongoClient;
import io.quarkus.mongodb.reactive.ReactiveMongoCollection;
import io.smallrye.mutiny.Uni;
import org.bson.Document;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;

@ApplicationScoped
public class ReactiveFruitService {

    @Inject
    ReactiveMongoClient mongoClient;

    public Uni<List<Fruit>> list() {
        return getCollection().find()
                .map(doc -> {
                    Fruit fruit = new Fruit();
                    fruit.setName(doc.getString("name"));
                    fruit.setDescription(doc.getString("description"));
                    return fruit;
                }).collect().asList();
    }

    public Uni<Void> add(Fruit fruit) {
        Document document = new Document()
                .append("name", fruit.getName())
                .append("description", fruit.getDescription());
        return getCollection().insertOne(document)
                .onItem().ignore().andContinueWithNull();
    }

    private ReactiveMongoCollection<Document> getCollection() {
        return mongoClient.getDatabase("fruit").getCollection("fruit");
    }
}
package org.acme.mongodb;

import io.smallrye.mutiny.Uni;

import java.util.List;

import jakarta.inject.Inject;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.core.MediaType;

@Path("/reactive_fruits")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ReactiveFruitResource {

    @Inject
    ReactiveFruitService fruitService;

    @GET
    public Uni<List<Fruit>> list() {
        return fruitService.list();
    }

    @POST
    public Uni<List<Fruit>> add(Fruit fruit) {
        return fruitService.add(fruit)
                .onItem().ignore().andSwitchTo(this::list);
    }
}

BSON codecを使ってMongoDBクライアントの利用をシンプルにする

Bson Codec を使用することで、MongoDB クライアントは自動的に MongoDB Document への/からのドメインオブジェクトの変換の世話をします。

まず、Bson Codec を作成する必要があります。これは、エンティティーを MongoDB Document に変換する方法を Bson に伝えます。ここでは CollectibleCodec を使用しています。私たちのオブジェクトはデータベースから取得可能なので (MongoDB の識別子を持っています)、そうでなければ Codec を使用します。詳細はcodecのドキュメントを参照ください: https://mongodb.github.io/mongo-java-driver/3.10/bson/codecs

package org.acme.mongodb.codec;

import com.mongodb.MongoClientSettings;
import org.acme.mongodb.Fruit;
import org.bson.Document;
import org.bson.BsonWriter;
import org.bson.BsonValue;
import org.bson.BsonReader;
import org.bson.BsonString;
import org.bson.codecs.Codec;
import org.bson.codecs.CollectibleCodec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;

import java.util.UUID;

public class FruitCodec implements CollectibleCodec<Fruit> {

    private final Codec<Document> documentCodec;

    public FruitCodec() {
        this.documentCodec = MongoClientSettings.getDefaultCodecRegistry().get(Document.class);
    }

    @Override
    public void encode(BsonWriter writer, Fruit fruit, EncoderContext encoderContext) {
        Document doc = new Document();
        doc.put("name", fruit.getName());
        doc.put("description", fruit.getDescription());
        documentCodec.encode(writer, doc, encoderContext);
    }

    @Override
    public Class<Fruit> getEncoderClass() {
        return Fruit.class;
    }

    @Override
    public Fruit generateIdIfAbsentFromDocument(Fruit document) {
        if (!documentHasId(document)) {
            document.setId(UUID.randomUUID().toString());
        }
        return document;
    }

    @Override
    public boolean documentHasId(Fruit document) {
        return document.getId() != null;
    }

    @Override
    public BsonValue getDocumentId(Fruit document) {
        return new BsonString(document.getId());
    }

    @Override
    public Fruit decode(BsonReader reader, DecoderContext decoderContext) {
        Document document = documentCodec.decode(reader, decoderContext);
        Fruit fruit = new Fruit();
        if (document.getString("id") != null) {
            fruit.setId(document.getString("id"));
        }
        fruit.setName(document.getString("name"));
        fruit.setDescription(document.getString("description"));
        return fruit;
    }
}

そして、この CodecFruit クラスにリンクさせるための CodecProvider を作成する必要があります。

package org.acme.mongodb.codec;

import org.acme.mongodb.Fruit;
import org.bson.codecs.Codec;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistry;

public class FruitCodecProvider implements CodecProvider {
    @Override
    public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
        if (clazz.equals(Fruit.class)) {
            return (Codec<T>) new FruitCodec();
        }
        return null;
    }

}

Quarkusは、 CodecProvider@Singleton スコープのCDIビーンとして登録する作業を行います。

最後に、データベースから MongoCollection を取得するとき、 Document の代わりに Fruit クラスを直接使用することができます。codecは自動的に DocumentFruit クラスにマッピングします。

これが、 MongoCollectionFruitCodec と使用する例です。

package org.acme.mongodb;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.List;

@ApplicationScoped
public class CodecFruitService {

    @Inject MongoClient mongoClient;

    public List<Fruit> list(){
        List<Fruit> list = new ArrayList<>();
        MongoCursor<Fruit> cursor = getCollection().find().iterator();

        try {
            while (cursor.hasNext()) {
                list.add(cursor.next());
            }
        } finally {
            cursor.close();
        }
        return list;
    }

    public void add(Fruit fruit){
        getCollection().insertOne(fruit);
    }

    private MongoCollection<Fruit> getCollection(){
        return mongoClient.getDatabase("fruit").getCollection("fruit", Fruit.class);
    }
}

POJO codec

POJO codec は、POJOをMongoDBコレクションにマッピングする方法をカスタマイズできるアノテーションのセットを提供しています。このCodecはQuarkusによって自動的に初期化されます。

このアノテーションのひとつに @BsonDiscriminator アノテーションがありますが、これは、ドキュメントの中にデリミタフィールドを追加することで、複数の Java 型をひとつの MongoDB コレクションに保存できるようにするものです。抽象的な型やインターフェイスを扱うときに便利です。

Quarkusは、 @BsonDiscriminator でアノテーションされたすべてのクラスをPOJO codecで自動的に登録します。

POJO Codecでは、 PropertyCodecProvider によるジェネリックサポートが強化されています。Quarkusでは、POJO Codecで PropertyCodecProvider を使用すると自動的に登録されます(これらのクラスは自動的に @Singleton スコープのCDI Beanになります)。ネイティブ実行可能ファイルをビルドしてジェネリック型を使用する場合、リフレクションのために型の引数を登録する必要があるかもしれません。

PanacheでMongoDBをシンプルにする

MongoDB with Panacheエクステンションは、 Hibernate ORM with Panache にあるようなアクティブレコードスタイルのエンティティ(およびリポジトリ)を提供することで、MongoDBの利用を促進し、Quarkusでエンティティを簡単に楽しく書けるようにすることに重点を置いています。

Liquibaseによるスキーママイグレーション

Liquibase MongoDB エクステンションは、インデックスと初期データを含む MongoDB データベースの初期化を容易にします。 Liquibase が SQL データベースに提供するものと同じスキーママイグレーション機能を実装しています。

接続のヘルスチェック

quarkus-smallrye-health エクステンションを使用している場合、 quarkus-mongodb-client はクラスターへの接続を検証するためのReadinessヘルスチェックを自動的に追加します。

そのため、アプリケーションの /q/health/ready エンドポイントにアクセスすると、接続の検証状況に関する情報が表示されます。

この動作は、 application.propertiesquarkus.mongodb.health.enabled プロパティーを false に設定することで無効にできます。

メトリクス

quarkus-micrometer または quarkus-smallrye-metrics エクステンションを使用している場合、 quarkus-mongodb-client は接続プールに関するメトリクスを提供することができます。この動作を有効にするには、まず application.propertiesquarkus.mongodb.metrics.enabled プロパティーを true に設定する必要があります。

そのため、アプリケーションの /q/metrics エンドポイントにアクセスすると、接続プールの状況に関する情報が表示されます。SmallRye Metricsを使用すると、接続プールのメトリクスは vendor スコープの配下で利用可能になっています。

テストヘルパー

Dev Services for MongoDB は、ユニットテスト用のMongoDBデータベースを起動するための最適なオプションです。

しかし、それを使用できない場合は、Quarkus が提供する 2 つの QuarkusTestResourceLifecycleManager のいずれかを使用して MongoDB データベースを開始できます。 彼らは Flapdoodle embedded MongoDB に依存しています。

  • io.quarkus.test.mongodb.MongoTestResource は、ポート27017に単一のインスタンスを起動します。

  • io.quarkus.test.mongodb.MongoReplicaSetTestResource は、ポート27017とポート27018にある2つのインスタンスでレプリカセットを開始します。

これらを使用するには、 io.quarkus:quarkus-test-mongodb の依存関係を pom.xml に追加する必要があります。

QuarkusTestResourceLifecycleManager の使い方については、 Quarkusのテストリソースをご覧ください。

MongoDB が起動時にリッスンする希望のポートを設定するには、次のコードを使用します。

@QuarkusTestResource(value = MongoTestResource.class, initArgs = @ResourceArg(name = MongoTestResource.PORT, value = "27017"))

起動するMongoDBのバージョンを任意に設定するには、次のコードを使用します。

@QuarkusTestResource(value = MongoTestResource.class, initArgs = @ResourceArg(name = MongoTestResource.VERSION, value = "V5_0"))

使用する文字列の値は de.flapdoodle.embed.mongo.distribution.Version または de.flapdoodle.embed.mongo.distribution.Version.Main のいずれかの列挙型になります。 バージョンを指定しない場合、デフォルトで Version.Main.V4_0 が使用されます。

レガシークライアント

デフォルトではレガシーな MongoDB クライアントは含まれていません。今では引退した MongoDB Java API (DB, DBCollection, …​ ) と com.mongodb.MongoClient が含まれていますが、今では com.mongodb.client.MongoClient に取って代わられています。

レガシーAPIを使用したい場合は、次の依存関係をビルドファイルに追加する必要があります。

pom.xml
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-legacy</artifactId>
</dependency>
build.gradle
implementation("org.mongodb:mongodb-driver-legacy")

ネイティブ実行可能ファイルの構築

MongoDBクライアントをネイティブ実行可能ファイルで使うことができます。

SSL/TLS 暗号化を使用したい場合は、これらのプロパティを application.properties に追加する必要があります。

quarkus.mongodb.tls=true
quarkus.mongodb.tls-insecure=true # only if TLS certificate cannot be validated

その後、通常のコマンドでネイティブ実行可能ファイルをビルドすることができます。

コマンドラインインタフェース
quarkus build --native
Maven
./mvnw install -Dnative
Gradle
./gradlew build -Dquarkus.package.type=native

実行は ./target/mongodb-quickstart-1.0-SNAPSHOT-runner を実行するだけで簡単です。

その後、ブラウザで http://localhost:8080/fruits.html を開き、アプリケーションを使用します。

現在、Quarkusはネイティブモードでの Client-Side Field Level Encryptionをサポートしていません。

アプリケーションをネイティブモードで実行した際に、以下のようなエラーが発生した場合があります。+ Failed to encode 'MyObject'. Encoding 'myVariable' errored with: Can’t find a codec for class org.acme.MyVariable. + これは、 org.acme.MyVariable クラスがGraalVMに知られていないことを意味しています。対策としては、 @RegisterForReflection アノテーションを MyVariable class に追加してください。 @RegisterForReflection アノテーションの詳細については、 ネイティブアプリケーションのヒントのページをご覧ください。

mongo+srv://のURLの使用

mongo+srv:// url は、JVM モードではサポートされます。しかし、ネイティブモードでは、MongoDB クライアントが提供するデフォルトの DNS リゾルバは JNDI を使っているので動作しません。

mongo+srv:// をネイティブモードで使用する必要がある場合は、代替の DNS リゾルバを設定することができます。この機能は *実験的な*もので、JVMアプリケーションとネイティブアプリケーションの間に違いが生じる可能性があります。

代替のDNSリゾルバを有効にするには

quarkus.mongodb.native.dns.use-vertx-dns-resolver=true

プロパティ名で示されているように、Vert.xを使用してDNSレコードを取得します。デフォルトでは、 /etc/resolv.conf から最初の nameserver を読み取ろうとします。このファイルが存在する場合は、そのファイルを使用します。また、DNS サーバーを設定することもできます。

quarkus.mongodb.native.dns.use-vertx-dns-resolver=true
quarkus.mongodb.native.dns.server-host=10.0.0.1
quarkus.mongodb.native.dns.server-port=53 # 53 is the default port

また、ルックアップのタイムアウトは、以下の方法で設定できます。

quarkus.mongodb.native.dns.use-vertx-dns-resolver=true
quarkus.mongodb.native.dns.lookup-timeout=10s # the default is 5s

Customize the Mongo client configuration programmatically

If you need to customize the Mongo client configuration programmatically, you need to implement the io.quarkus.mongodb.runtime.MongoClientCustomizer interface and expose it as a CDI application scoped bean:

@ApplicationScoped
public class MyCustomizer implements MongoClientCustomizer {

    @Override
    public MongoClientSettings.Builder customize(MongoClientSettings.Builder builder) {
        return builder.applicationName("my-app");
    }
}

The bean can customize a specific client using the @MongoClientName qualifier to indicate the client name. When there is no qualifier, it customizes the default client. At most one customizer can be used per client. If multiple customizers targeting the same client are detected, an exception is thrown at build time.

This feature can be used to configure client-side field level encryption (CSFLE). Follows the instructions from the Mongo web site to configure CSFLE:

@ApplicationScoped
public class MyCustomizer implements MongoClientCustomizer {
    @Override
    public MongoClientSettings.Builder customize(MongoClientSettings.Builder builder) {
        Map<String, Map<String, Object>> kmsProviders = getKmsProviders();
        String dek = getDataEncryptionKey();
        Map<String, BsonDocument> schema = getSchema(dek);

        Map<String, Object> extraOptions = new HashMap<>();
        extraOptions.put("cryptSharedLibPath", "<path to crypt shared library>");

        return builder.autoEncryptionSettings(AutoEncryptionSettings.builder()
                .keyVaultNamespace(KEY_VAULT_NAMESPACE)
                .kmsProviders(kmsProviders)
                .schemaMap(schemaMap)
                .extraOptions(extraOptions)
                .build());
    }
}
Client-side field level encryption, and feature relying on Mongo Crypt in general, are not supported in native mode.

設定リファレンス

ビルド時に固定される構成プロパティ - 他のすべての構成プロパティは実行時にオーバーライド可能

Configuration property

デフォルト

Whether a health check is published in case the smallrye-health extension is present.

Environment variable: QUARKUS_MONGODB_HEALTH_ENABLED

Show more

boolean

true

Whether metrics are published in case a metrics extension is present.

Environment variable: QUARKUS_MONGODB_METRICS_ENABLED

Show more

boolean

false

If set to true, the default clients will always be created even if there are no injection points that use them

Environment variable: QUARKUS_MONGODB_FORCE_DEFAULT_CLIENTS

Show more

boolean

false

If DevServices has been explicitly enabled or disabled. DevServices is generally enabled by default, unless there is an existing configuration present. When DevServices is enabled Quarkus will attempt to automatically configure and start a database when running in Dev or Test mode.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_ENABLED

Show more

boolean

The container image name to use, for container based DevServices providers.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_IMAGE_NAME

Show more

string

Optional fixed port the dev service will listen to.

If not defined, the port will be chosen randomly.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_PORT

Show more

int

Configures the connection string. The format is: mongodb://[username:password@]host1[:port1][,host2[:port2],…​[,hostN[:portN]]][/[database.collection][?options]]

mongodb:// is a required prefix to identify that this is a string in the standard connection format.

username:password@ are optional. If given, the driver will attempt to log in to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as well.

host1 is the only required part of the connection string. It identifies a server address to connect to.

:portX is optional and defaults to :27017 if not provided.

/database is the name of the database to log in to and thus is only relevant if the username:password@ syntax is used. If not specified the admin database will be used by default.

?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the options. Options are name=value pairs and the pairs are separated by "&".

An alternative format, using the mongodb+srv protocol, is:

mongodb+srv://[username:password@]host[/[database][?options]]
  • mongodb+srv:// is a required prefix for this format.

  • username:password@ are optional. If given, the driver will attempt to login to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as well

  • host is the only required part of the URI. It identifies a single host name for which SRV records are looked up from a Domain Name Server after prefixing the host name with "_mongodb._tcp". The host/port for each SRV record becomes the seed list used to connect, as if each one were provided as host/port pair in a URI using the normal mongodb protocol.

  • /database is the name of the database to login to and thus is only relevant if the username:password@ syntax is used. If not specified the "admin" database will be used by default.

  • ?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the options. Options are name=value pairs and the pairs are separated by "&". Additionally with the mongodb+srv protocol, TXT records are looked up from a Domain Name Server for the given host, and the text value of each one is prepended to any options on the URI itself. Because the last specified value for any option wins, that means that options provided on the URI will override any that are provided via TXT records.

Environment variable: QUARKUS_MONGODB_CONNECTION_STRING

Show more

string

Configures the MongoDB server addressed (one if single mode). The addresses are passed as host:port.

Environment variable: QUARKUS_MONGODB_HOSTS

Show more

list of string

127.0.0.1:27017

Configure the database name.

Environment variable: QUARKUS_MONGODB_DATABASE

Show more

string

Configures the application name.

Environment variable: QUARKUS_MONGODB_APPLICATION_NAME

Show more

string

Configures the maximum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB_MAX_POOL_SIZE

Show more

int

Configures the minimum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB_MIN_POOL_SIZE

Show more

int

Maximum idle time of a pooled connection. A connection that exceeds this limit will be closed.

Environment variable: QUARKUS_MONGODB_MAX_CONNECTION_IDLE_TIME

Show more

Duration

Maximum lifetime of a pooled connection. A connection that exceeds this limit will be closed.

Environment variable: QUARKUS_MONGODB_MAX_CONNECTION_LIFE_TIME

Show more

Duration

Configures the time period between runs of the maintenance job.

Environment variable: QUARKUS_MONGODB_MAINTENANCE_FREQUENCY

Show more

Duration

Configures period of time to wait before running the first maintenance job on the connection pool.

Environment variable: QUARKUS_MONGODB_MAINTENANCE_INITIAL_DELAY

Show more

Duration

How long a connection can take to be opened before timing out.

Environment variable: QUARKUS_MONGODB_CONNECT_TIMEOUT

Show more

Duration

How long a socket read can take before timing out.

Environment variable: QUARKUS_MONGODB_READ_TIMEOUT

Show more

Duration

If connecting with TLS, this option enables insecure TLS connections.

Environment variable: QUARKUS_MONGODB_TLS_INSECURE

Show more

boolean

false

Whether to connect using TLS.

Environment variable: QUARKUS_MONGODB_TLS

Show more

boolean

false

Implies that the hosts given are a seed list, and the driver will attempt to find all members of the set.

Environment variable: QUARKUS_MONGODB_REPLICA_SET_NAME

Show more

string

How long the driver will wait for server selection to succeed before throwing an exception.

Environment variable: QUARKUS_MONGODB_SERVER_SELECTION_TIMEOUT

Show more

Duration

When choosing among multiple MongoDB servers to send a request, the driver will only send that request to a server whose ping time is less than or equal to the server with the fastest ping time plus the local threshold.

Environment variable: QUARKUS_MONGODB_LOCAL_THRESHOLD

Show more

Duration

The frequency that the driver will attempt to determine the current state of each server in the cluster.

Environment variable: QUARKUS_MONGODB_HEARTBEAT_FREQUENCY

Show more

Duration

Configures the read concern. Supported values are: local|majority|linearizable|snapshot|available

Environment variable: QUARKUS_MONGODB_READ_CONCERN

Show more

string

Configures the read preference. Supported values are: primary|primaryPreferred|secondary|secondaryPreferred|nearest

Environment variable: QUARKUS_MONGODB_READ_PREFERENCE

Show more

string

The database used during the readiness health checks

Environment variable: QUARKUS_MONGODB_HEALTH_DATABASE

Show more

string

admin

Configures the UUID representation to use when encoding instances of java.util.UUID and when decoding BSON binary values with subtype of 3.

Environment variable: QUARKUS_MONGODB_UUID_REPRESENTATION

Show more

unspecified, standard, c-sharp-legacy, java-legacy, python-legacy

This property configures the DNS server. If the server is not set, it tries to read the first nameserver from /etc /resolv.conf (if the file exists), otherwise fallback to the default.

Environment variable: QUARKUS_MONGODB_DNS_SERVER_HOST

Show more

string

This property configures the DNS server port.

Environment variable: QUARKUS_MONGODB_DNS_SERVER_PORT

Show more

int

53

If native.dns.use-vertx-dns-resolver is set to true, this property configures the DNS lookup timeout duration.

Environment variable: QUARKUS_MONGODB_DNS_LOOKUP_TIMEOUT

Show more

Duration

5S

This property enables the logging ot the DNS lookup. It can be useful to understand why the lookup fails.

Environment variable: QUARKUS_MONGODB_DNS_LOG_ACTIVITY

Show more

boolean

false

Generic properties that are added to the connection URL.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_PROPERTIES

Show more

Map<String,String>

Environment variables that are passed to the container.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_CONTAINER_ENV

Show more

Map<String,String>

Configures the connection string. The format is: mongodb://[username:password@]host1[:port1][,host2[:port2],…​[,hostN[:portN]]][/[database.collection][?options]]

mongodb:// is a required prefix to identify that this is a string in the standard connection format.

username:password@ are optional. If given, the driver will attempt to log in to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as well.

host1 is the only required part of the connection string. It identifies a server address to connect to.

:portX is optional and defaults to :27017 if not provided.

/database is the name of the database to log in to and thus is only relevant if the username:password@ syntax is used. If not specified the admin database will be used by default.

?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the options. Options are name=value pairs and the pairs are separated by "&".

An alternative format, using the mongodb+srv protocol, is:

mongodb+srv://[username:password@]host[/[database][?options]]
  • mongodb+srv:// is a required prefix for this format.

  • username:password@ are optional. If given, the driver will attempt to login to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as well

  • host is the only required part of the URI. It identifies a single host name for which SRV records are looked up from a Domain Name Server after prefixing the host name with "_mongodb._tcp". The host/port for each SRV record becomes the seed list used to connect, as if each one were provided as host/port pair in a URI using the normal mongodb protocol.

  • /database is the name of the database to login to and thus is only relevant if the username:password@ syntax is used. If not specified the "admin" database will be used by default.

  • ?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the options. Options are name=value pairs and the pairs are separated by "&". Additionally with the mongodb+srv protocol, TXT records are looked up from a Domain Name Server for the given host, and the text value of each one is prepended to any options on the URI itself. Because the last specified value for any option wins, that means that options provided on the URI will override any that are provided via TXT records.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CONNECTION_STRING

Show more

string

Configures the MongoDB server addressed (one if single mode). The addresses are passed as host:port.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__HOSTS

Show more

list of string

127.0.0.1:27017

Configure the database name.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__DATABASE

Show more

string

Configures the application name.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__APPLICATION_NAME

Show more

string

Configures the maximum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAX_POOL_SIZE

Show more

int

Configures the minimum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MIN_POOL_SIZE

Show more

int

Maximum idle time of a pooled connection. A connection that exceeds this limit will be closed.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAX_CONNECTION_IDLE_TIME

Show more

Duration

Maximum lifetime of a pooled connection. A connection that exceeds this limit will be closed.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAX_CONNECTION_LIFE_TIME

Show more

Duration

Configures the time period between runs of the maintenance job.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAINTENANCE_FREQUENCY

Show more

Duration

Configures period of time to wait before running the first maintenance job on the connection pool.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAINTENANCE_INITIAL_DELAY

Show more

Duration

How long a connection can take to be opened before timing out.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CONNECT_TIMEOUT

Show more

Duration

How long a socket read can take before timing out.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__READ_TIMEOUT

Show more

Duration

If connecting with TLS, this option enables insecure TLS connections.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__TLS_INSECURE

Show more

boolean

false

Whether to connect using TLS.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__TLS

Show more

boolean

false

Implies that the hosts given are a seed list, and the driver will attempt to find all members of the set.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__REPLICA_SET_NAME

Show more

string

How long the driver will wait for server selection to succeed before throwing an exception.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__SERVER_SELECTION_TIMEOUT

Show more

Duration

When choosing among multiple MongoDB servers to send a request, the driver will only send that request to a server whose ping time is less than or equal to the server with the fastest ping time plus the local threshold.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__LOCAL_THRESHOLD

Show more

Duration

The frequency that the driver will attempt to determine the current state of each server in the cluster.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__HEARTBEAT_FREQUENCY

Show more

Duration

Configures the read concern. Supported values are: local|majority|linearizable|snapshot|available

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__READ_CONCERN

Show more

string

Configures the read preference. Supported values are: primary|primaryPreferred|secondary|secondaryPreferred|nearest

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__READ_PREFERENCE

Show more

string

The database used during the readiness health checks

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__HEALTH_DATABASE

Show more

string

admin

Configures the UUID representation to use when encoding instances of java.util.UUID and when decoding BSON binary values with subtype of 3.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__UUID_REPRESENTATION

Show more

unspecified, standard, c-sharp-legacy, java-legacy, python-legacy

Write concern

デフォルト

Configures the safety. If set to true: the driver ensures that all writes are acknowledged by the MongoDB server, or else throws an exception. (see also w and wtimeoutMS). If set fo - false: the driver does not ensure that all writes are acknowledged by the MongoDB server.

Environment variable: QUARKUS_MONGODB_WRITE_CONCERN_SAFE

Show more

boolean

true

Configures the journal writing aspect. If set to true: the driver waits for the server to group commit to the journal file on disk. If set to false: the driver does not wait for the server to group commit to the journal file on disk.

Environment variable: QUARKUS_MONGODB_WRITE_CONCERN_JOURNAL

Show more

boolean

true

When set, the driver adds w: wValue to all write commands. It requires safe to be true. The value is typically a number, but can also be the majority string.

Environment variable: QUARKUS_MONGODB_WRITE_CONCERN_W

Show more

string

If set to true, the driver will retry supported write operations if they fail due to a network error.

Environment variable: QUARKUS_MONGODB_WRITE_CONCERN_RETRY_WRITES

Show more

boolean

false

When set, the driver adds wtimeout : ms to all write commands. It requires safe to be true.

Environment variable: QUARKUS_MONGODB_WRITE_CONCERN_W_TIMEOUT

Show more

Duration

Configures the safety. If set to true: the driver ensures that all writes are acknowledged by the MongoDB server, or else throws an exception. (see also w and wtimeoutMS). If set fo - false: the driver does not ensure that all writes are acknowledged by the MongoDB server.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__WRITE_CONCERN_SAFE

Show more

boolean

true

Configures the journal writing aspect. If set to true: the driver waits for the server to group commit to the journal file on disk. If set to false: the driver does not wait for the server to group commit to the journal file on disk.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__WRITE_CONCERN_JOURNAL

Show more

boolean

true

When set, the driver adds w: wValue to all write commands. It requires safe to be true. The value is typically a number, but can also be the majority string.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__WRITE_CONCERN_W

Show more

string

If set to true, the driver will retry supported write operations if they fail due to a network error.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__WRITE_CONCERN_RETRY_WRITES

Show more

boolean

false

When set, the driver adds wtimeout : ms to all write commands. It requires safe to be true.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__WRITE_CONCERN_W_TIMEOUT

Show more

Duration

Credentials and authentication mechanism

デフォルト

Configures the username.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_USERNAME

Show more

string

Configures the password.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_PASSWORD

Show more

string

Configures the authentication mechanism to use if a credential was supplied. The default is unspecified, in which case the client will pick the most secure mechanism available based on the sever version. For the GSSAPI and MONGODB-X509 mechanisms, no password is accepted, only the username. Supported values: null or GSSAPI|PLAIN|MONGODB-X509|SCRAM_SHA_1|SCRAM_SHA_256|MONGODB_AWS

Environment variable: QUARKUS_MONGODB_CREDENTIALS_AUTH_MECHANISM

Show more

string

Configures the source of the authentication credentials. This is typically the database where the credentials have been created. The value defaults to the database specified in the path portion of the connection string or in the 'database' configuration property. If the database is specified in neither place, the default value is admin. This option is only respected when using the MONGO-CR mechanism (the default).

Environment variable: QUARKUS_MONGODB_CREDENTIALS_AUTH_SOURCE

Show more

string

The credentials provider name

Environment variable: QUARKUS_MONGODB_CREDENTIALS_CREDENTIALS_PROVIDER

Show more

string

The credentials provider bean name.

This is a bean name (as in @Named) of a bean that implements CredentialsProvider. It is used to select the credentials provider bean when multiple exist. This is unnecessary when there is only one credentials provider available.

For Vault, the credentials provider bean name is vault-credentials-provider.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_CREDENTIALS_PROVIDER_NAME

Show more

string

Allows passing authentication mechanism properties.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_AUTH_MECHANISM_PROPERTIES

Show more

Map<String,String>

Configures the username.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_USERNAME

Show more

string

Configures the password.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_PASSWORD

Show more

string

Configures the authentication mechanism to use if a credential was supplied. The default is unspecified, in which case the client will pick the most secure mechanism available based on the sever version. For the GSSAPI and MONGODB-X509 mechanisms, no password is accepted, only the username. Supported values: null or GSSAPI|PLAIN|MONGODB-X509|SCRAM_SHA_1|SCRAM_SHA_256|MONGODB_AWS

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_AUTH_MECHANISM

Show more

string

Configures the source of the authentication credentials. This is typically the database where the credentials have been created. The value defaults to the database specified in the path portion of the connection string or in the 'database' configuration property. If the database is specified in neither place, the default value is admin. This option is only respected when using the MONGO-CR mechanism (the default).

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_AUTH_SOURCE

Show more

string

Allows passing authentication mechanism properties.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_AUTH_MECHANISM_PROPERTIES

Show more

Map<String,String>

The credentials provider name

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_CREDENTIALS_PROVIDER

Show more

string

The credentials provider bean name.

This is a bean name (as in @Named) of a bean that implements CredentialsProvider. It is used to select the credentials provider bean when multiple exist. This is unnecessary when there is only one credentials provider available.

For Vault, the credentials provider bean name is vault-credentials-provider.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_CREDENTIALS_PROVIDER_NAME

Show more

string

期間フォーマットについて

To write duration values, use the standard java.time.Duration format. See the Duration#parse() Java API documentation for more information.

数字で始まる簡略化した書式を使うこともできます:

  • 数値のみの場合は、秒単位の時間を表します。

  • 数値の後に ms が続く場合は、ミリ秒単位の時間を表します。

その他の場合は、簡略化されたフォーマットが解析のために java.time.Duration フォーマットに変換されます:

  • 数値の後に hms が続く場合は、その前に PT が付けられます。

  • 数値の後に d が続く場合は、その前に P が付けられます。

関連コンテンツ