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.12

  • 使用したい場合は、 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='rest-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.31.1:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=mongodb-quickstart \
    -Dextensions='rest-jackson,mongodb-client' \
    -DnoCode
cd mongodb-quickstart

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

Windowsユーザーの場合:

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

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

このコマンドは、Quarkus REST (旧称 RESTEasy Reactive) Jackson および MongoDB クライアントエクステンションをインポートする 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

mongo+srv:// URL の解決

mongo+srv:// URL を使う場合、MongoDB ドライバは DNS SRV レコードを解決して接続するホストの一覧を取得します。デフォルトでは、JNDI を使って実装された DNS クライアントに依存します。

セキュリティ上の理由から、Quarkusでは、Log4Shellのような潜在的な脆弱性を軽減するために、アプリケーション内でのJNDIの使用を制限しています。 mongo+srv:// をサポートするために、Quarkusは代替のDNSクライアントを提供しています。

しかし、環境によってはこの代替 DNS クライアントが SRV レコードを解決できないことがあります。そのような問題が発生した場合は、次のプロパティを設定することで MongoDB ドライバのデフォルト DNS クライアントに戻すことができます:

quarkus.naming.enable-jndi=true
quarkus.class-loading.removed-resources."io.quarkus\:quarkus-mongodb-client"=META-INF/services/com.mongodb.spi.dns.DnsClientProvider

これは MongoDB ドライバが使うデフォルトの JNDI ベースの解決メカニズムを復元します。

MongoDB Dev Services の使用

MongoDB Dev Services を参照してください。

複数の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;

Activate or deactivate Mongo Clients

When a Mongo Client is configured at build time, and its URL is set at runtime, it is active by default. Quarkus starts the corresponding Mongo Client when the application starts.

To deactivate a Mongo Client at runtime, either:

  • Do not set quarkus.mongodb[.optional name].hosts or quarkus.mongodb[.optional name].connection-string.

  • Set quarkus.mongodb[.optional name].active to false.

If a Mongo Client is not active:

  • The Mongo Client does not attempt to connect to Mongo during application startup.

  • The Mongo Client does not contribute a health check.

  • Static CDI injection points involving the Mongo Client, such as @Inject ReactiveMongoClient mongoClient or @Inject MongoClient mongoClient, cause application startup to fail.

  • Dynamic retrieval of the Mongo Client, such as through CDI.getBeanContainer(), Arc.instance(), or an injected Instance<ReactiveMongoClient>, causes an exception to be thrown.

  • Other Quarkus extensions that consume the Mongo Client may cause application startup to fail.

This feature is especially useful when the application must dynamically select a Mongo Client from a predefined set at runtime.

An example of configuring multiple Mongo Clients for runtime selection:
quarkus.mongodb.one.active=false
quarkus.mongodb.one.connection-string=mongodb://127.0.0.1:27018
quarkus.mongodb.two.active=false
quarkus.mongodb.two.connection-string=mongodb://127.0.0.1:27019
import io.quarkus.arc.InjectableInstance;

import com.mongodb.client.MongoClient;
import io.quarkus.mongodb.reactive.ReactiveMongoClient;

@ApplicationScoped
public class MyConsumer {
    @Inject
    @MongoClientName("one")
    InjectableInstance<ReactiveMongoClient> one;
    @Inject
    @MongoClientName("two")
    InjectableInstance<MongoClient> two;
    public void doSomething() {
        ReactiveMongoClient mongoClient = one.getActive();
        // ...
    }
}

Setting quarkus.mongodb.one.active=true at runtime makes only the Mongo Client one available. Setting quarkus.mongodb.two.active=true at runtime makes only the Mongo Client two available.

A Mongo Client (either default or named) must always be discoverable at build-time to be considered for runtime injection. This can be done by injecting the Mongo Client name with @MongoClientName. If the Mongo Client name may be active or inactive, it needs to use the wrapper InjectableInstance<>, or else Quarkus will throw an exception at startup time if the Mongo Client is inactive. Alternatively, Mongo Clients may also be discovered via configuration.

MongoDB データベースの実行

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

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

docker run -ti --rm -p 27017:27017 docker.io/library/mongo:7.0

Dev Services を使用する場合、コンテナーを手動で起動する必要はありません。

フロントエンドの作成

それでは、 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 コレクションにマッピングする方法をカスタマイズできる一連のアノテーションを提供します。このコーデックは Quarkus によって自動的に初期化されます。 このコーデックは Java レコードもサポートしているため、POJO または POJO の属性に使用できます。

このアノテーションのひとつに @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 に設定することで無効にできます。

メトリクス

If you are using the quarkus-micrometer, quarkus-mongodb-client can provide metrics about the connection pools. This behavior must first be enabled by setting the quarkus.mongodb.metrics.enabled property to true in your application.properties.

So when you access the /q/metrics endpoint of your application you will have information about the connection pool status.

トレース

MongoDB でトレースを使用するには、プロジェクトに quarkus-opentelemetry エクステンションを追加する必要があります。

すべてのトレースインフラストラクチャーが整っていても、mongodb トレースはデフォルトでは有効になっていないため、次のプロパティーを設定して有効にする必要があります。

# enable tracing
quarkus.mongodb.tracing.enabled=true

テストヘルパー

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")

TLSの設定

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

quarkus.mongodb.tls=true

TLSレジストリからtls設定を使用するようにクライアントを設定することもできます:

quarkus.tls.mongo.trust-store.pem.certs=certa.pem,certb.pem
quarkus.mongodb.tls-configuration-name=mongo

無効なホスト名の証明書を持つサーバを信頼するようにクライアントを設定できます:

quarkus.tls.mongo.hostname-verification-algorithm=NONE
quarkus.mongodb.tls-configuration-name=mongo

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

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

ネイティブ実行可能ファイルは、通常のコマンド ./mvnw package -Pnative でビルドできます。

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

実行は ./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 に認識されていないことを示しています。解決策は、 MyVariable クラスに @RegisterForReflection アノテーションを追加することです。 @RegisterForReflection アノテーションの詳細は、ネイティブアプリケーションのヒント ページを参照してください。

Mongo クライアント設定のプログラムによるカスタマイズ

Mongo クライアント設定をプログラムでカスタマイズする必要がある場合は、 io.quarkus.mongodb.runtime.MongoClientCustomizer インターフェイスを実装し、それを CDI アプリケーションスコープ Bean として公開する必要があります。

@ApplicationScoped
public class MyCustomizer implements MongoClientCustomizer {

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

Bean は、クライアント名を示す @MongoClientName 修飾子を使用して特定のクライアントをカスタマイズできます。 修飾子がない場合、Bean はデフォルトのクライアントをカスタマイズします。 クライアントごとに最大 1 つのカスタマイザーを使用できます。 同じクライアントを対象とする複数のカスタマイザーが検出されると、ビルド時に例外が出力されます。

この機能を使用して、Client-Side Field Level Encryption (CSFLE) を設定できます。 CSFLE を設定するには、 Mongo Web サイト の手順に従います。

@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、および一般に Mongo Crypt に依存する機能は、ネイティブモードではサポートされていません。

設定リファレンス

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

Configuration property

タイプ

デフォルト

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

Environment variable: QUARKUS_MONGODB_HEALTH_ENABLED

Show more

ブーリアン

true

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

Environment variable: QUARKUS_MONGODB_METRICS_ENABLED

Show more

ブーリアン

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

ブーリアン

false

Whether tracing spans of driver commands are sent in case the quarkus-opentelemetry extension is present.

Environment variable: QUARKUS_MONGODB_TRACING_ENABLED

Show more

ブーリアン

false

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

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

ブーリアン

false

quarkus.mongodb."mongo-client-name".active

Whether this Mongo Client should be active at runtime.

Environment variable: QUARKUS_MONGODB_ACTIVE

Show more

ブーリアン

true

quarkus.mongodb."mongo-client-name".connection-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_CONNECTION_STRING

Show more

string

quarkus.mongodb."mongo-client-name".hosts

Configures the MongoDB server addresses (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

quarkus.mongodb."mongo-client-name".database

Configure the database name.

Environment variable: QUARKUS_MONGODB_DATABASE

Show more

string

quarkus.mongodb."mongo-client-name".application-name

Configures the application name.

Environment variable: QUARKUS_MONGODB_APPLICATION_NAME

Show more

string

quarkus.mongodb."mongo-client-name".max-pool-size

Configures the maximum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB_MAX_POOL_SIZE

Show more

int

quarkus.mongodb."mongo-client-name".min-pool-size

Configures the minimum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB_MIN_POOL_SIZE

Show more

int

quarkus.mongodb."mongo-client-name".max-connection-idle-time

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 

quarkus.mongodb."mongo-client-name".max-connection-life-time

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 

quarkus.mongodb."mongo-client-name".maintenance-frequency

Configures the time period between runs of the maintenance job.

Environment variable: QUARKUS_MONGODB_MAINTENANCE_FREQUENCY

Show more

Duration 

quarkus.mongodb."mongo-client-name".maintenance-initial-delay

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 

quarkus.mongodb."mongo-client-name".connect-timeout

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

Environment variable: QUARKUS_MONGODB_CONNECT_TIMEOUT

Show more

Duration 

quarkus.mongodb."mongo-client-name".read-timeout

How long a socket read can take before timing out.

Environment variable: QUARKUS_MONGODB_READ_TIMEOUT

Show more

Duration 

quarkus.mongodb."mongo-client-name".tls

Whether to connect using TLS.

Environment variable: QUARKUS_MONGODB_TLS

Show more

ブーリアン

false

quarkus.mongodb."mongo-client-name".tls-configuration-name

The name of the TLS configuration to use.

If a name is configured, it uses the configuration from quarkus.tls.<name>.* If a name is configured, but no TLS configuration is found with that name then an error will be thrown.

The default TLS configuration is not used by default.

Environment variable: QUARKUS_MONGODB_TLS_CONFIGURATION_NAME

Show more

string

quarkus.mongodb."mongo-client-name".replica-set-name

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

quarkus.mongodb."mongo-client-name".server-selection-timeout

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 

quarkus.mongodb."mongo-client-name".local-threshold

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 

quarkus.mongodb."mongo-client-name".heartbeat-frequency

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 

quarkus.mongodb."mongo-client-name".read-concern

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

Environment variable: QUARKUS_MONGODB_READ_CONCERN

Show more

string

quarkus.mongodb."mongo-client-name".read-preference

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

Environment variable: QUARKUS_MONGODB_READ_PREFERENCE

Show more

string

quarkus.mongodb."mongo-client-name".health.database

The database used during the readiness health checks

Environment variable: QUARKUS_MONGODB_HEALTH_DATABASE

Show more

string

admin

quarkus.mongodb."mongo-client-name".uuid-representation

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

quarkus.mongodb."mongo-client-name".reactive-transport

Configures the reactive transport.

Environment variable: QUARKUS_MONGODB_REACTIVE_TRANSPORT

Show more

nettyUses a Netty-based transport re-using the existing Netty event loops., mongoWith a reactive driver it uses an async transport backed by a driver-managed thread pool.

nettyUses a Netty-based transport re-using the existing Netty event loops.

This property is deprecated: This resolver is always used.

The default DNS resolver used to handle mongo+srv:// urls cannot be used in a native executable. This option enables a fallback to use Vert.x to resolve the server names instead of JNDI. IMPORTANT: The resolution may be different in JVM mode using the default (JNDI-based) DNS resolver, and in native mode. This feature is experimental.

Environment variable: QUARKUS_MONGODB_NATIVE_DNS_USE_VERTX_DNS_RESOLVER

Show more

ブーリアン

false

quarkus.mongodb."mongo-client-name".tls-insecure

This property is deprecated since 3.21: in favor of configuration at the tls registry level. See tls-configuration-name() and quarkus tls registry hostname verification configuration quarkus.tls.hostname-verification-algorithm=NONE.

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

Environment variable: QUARKUS_MONGODB_TLS_INSECURE

Show more

ブーリアン

false

Dev Services

タイプ

デフォルト

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

ブーリアン

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

Environment variable: QUARKUS_MONGODB_DEVSERVICES_IMAGE_NAME

Show more

string

docker.io/library/mongo:7.0

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__PROPERTY_KEY_

Show more

Map<String,String>

Environment variables that are passed to the container.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_CONTAINER_ENV__ENVIRONMENT_VARIABLE_NAME_

Show more

Map<String,String>

Indicates if the MongoDB server managed by Quarkus Dev Services is shared. When shared, Quarkus looks for running containers using label-based service discovery. If a matching container is found, it is used, and so a second one is not started. Otherwise, Dev Services for MongoDB starts a new container.

The discovery uses the quarkus-dev-service-mongodb label. The value is configured using the service-name property.

Container sharing is only used in dev mode.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_SHARED

Show more

ブーリアン

true

The value of the quarkus-dev-service-mongodb label attached to the started container. This property is used when shared is set to true. In this case, before starting a container, Dev Services for MongoDB looks for a container with the quarkus-dev-service-mongodb label set to the configured value. If found, it will use this container instead of starting a new one. Otherwise it starts a new container with the quarkus-dev-service-mongodb label set to the specified value.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_SERVICE_NAME

Show more

string

mongodb

Write concern

タイプ

デフォルト

quarkus.mongodb."mongo-client-name".write-concern.safe

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

ブーリアン

true

quarkus.mongodb."mongo-client-name".write-concern.journal

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

ブーリアン

true

quarkus.mongodb."mongo-client-name".write-concern.w

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

quarkus.mongodb."mongo-client-name".write-concern.retry-writes

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

ブーリアン

false

quarkus.mongodb."mongo-client-name".write-concern.w-timeout

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 

Credentials and authentication mechanism

タイプ

デフォルト

quarkus.mongodb."mongo-client-name".credentials.username

Configures the username.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_USERNAME

Show more

string

quarkus.mongodb."mongo-client-name".credentials.password

Configures the password.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_PASSWORD

Show more

string

quarkus.mongodb."mongo-client-name".credentials.auth-mechanism

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

quarkus.mongodb."mongo-client-name".credentials.auth-source

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

quarkus.mongodb."mongo-client-name".credentials.auth-mechanism-properties."property-key"

Allows passing authentication mechanism properties.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_AUTH_MECHANISM_PROPERTIES__PROPERTY_KEY_

Show more

Map<String,String>

quarkus.mongodb."mongo-client-name".credentials.credentials-provider

The credentials provider name

Environment variable: QUARKUS_MONGODB_CREDENTIALS_CREDENTIALS_PROVIDER

Show more

string

quarkus.mongodb."mongo-client-name".credentials.credentials-provider-name

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

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

期間の値を書くには、標準の java.time.Duration フォーマットを使います。 詳細は Duration#parse() Java API documentation を参照してください。

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

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

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

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

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

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

関連コンテンツ