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分钟

  • 编辑器

  • 安装JDK 11以上版本并正确配置了 JAVA_HOME

  • Apache Maven 3.8.1+

  • 如果你愿意的话,还可以选择使用Quarkus CLI

  • 如果你想构建原生可执行程序,可以选择安装Mandrel或者GraalVM,并正确配置(或者使用Docker在容器中进行构建)

  • 安装了MongoDB或安装了Docker

架构

本指南中构建的应用程序非常简单:用户可以使用一个表单在列表中添加元素并更新列表。

浏览器和服务器之间的所有信息都被格式化为JSON。

这些元素被存储在MongoDB中。

解决方案

我们建议你按照下面几节的说明,一步一步地创建应用程序。但是,你也可以直接转到已完成的例子中。

克隆 Git 仓库。 git clone https://github.com/quarkusio/quarkus-quickstarts.git ,或者下载一个 存档

该解决方案位于 mongodb-quickstart 目录中。

创建Maven项目

首先,我们需要一个新的项目。使用以下命令创建一个新项目:

CLI
quarkus create app org.acme:mongodb-quickstart \
    --extension=resteasy-reactive-jackson,mongodb-client \
    --no-code
cd mongodb-quickstart

创建Grade项目,请添加 --gradle 或者 --gradle-kotlin-dsl 参数。

关于如何安装并使用Quarkus CLI的更多信息,请参考Quarkus CLI指南

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

创建Grade项目,请添加 -DbuildTool=gradle 或者 -DbuildTool=gradle-kotlin-dsl 参数。

该命令生成一个导入RESTEasy Reactive Jackson和MongoDB客户端扩展的Maven结构。在此之后, quarkus-mongodb-client 扩展已被添加到您的构建文件中。

如果你已经配置了你的Quarkus项目,你可以通过在你的项目基础目录下运行以下命令,将 mongodb-client 扩展添加到你的项目中:

CLI
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列表。

首先,让我们创建 Fruit 实体类,如下所示:

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数据库 store/load fruits。

package org.acme.mongodb;

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

import javax.enterprise.context.ApplicationScoped;
import javax.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();
    }
}

The implementation is pretty straightforward, and you just need to define your endpoints using the JAX-RS annotations and use the FruitService to list/add new fruits.

配置MongoDB数据库

The main property to configure is the URL to access to MongoDB. Almost all configuration can be included in the connection URI, so we advise you to do so. You can find more information in the MongoDB documentation: 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

在此示例中,我们在 localhost 上运行的单个实例:

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

如果你需要更多的配置属性,在本指南的末尾有一个完整的列表。

By default, Quarkus will restrict the use of JNDI within an application, as a precaution to try and mitigate any future vulnerabilities similar to Log4Shell. Because the mongo+srv protocol often used to connect to MongoDB requires JNDI, this protection is automatically disabled when using the MongoDB client extension.

开发服务(免配置数据库)。

Quarkus supports a feature called Dev Services that allows you to create various datasources without any config. In the case of MongoDB this support extends to the default MongoDB connection. What that means practically, is that if you have not configured quarkus.mongodb.connection-string Quarkus will automatically start a MongoDB container when running tests or dev mode, and automatically configure the connection.

当运行应用程序的生产版本时,MongoDB连接需要正常配置,如果您希望在 application.properties 中包含生产数据库配置并继续使用开发服务,我们建议你使用 %prod. 配置文件来定义你的MongoDB设置。

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

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

boolean

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

Environment variable: QUARKUS_MONGODB_DEVSERVICES_IMAGE_NAME

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

int

Generic properties that are added to the connection URL.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_PROPERTIES

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] 。如果省略了名称,则配置默认的客户端。

The use of multiple MongoDB clients enables multi-tenancy for MongoDB by allowing to connect to multiple MongoDB clusters. + If you want to connect to multiple databases inside the same cluster, multiple clients are not necessary as a single client is able to access all databases in the same cluster (as a JDBC connection is able to access to multiple schemas inside the same database).

以Mongo客户端的名字进行注入

当使用多个客户端时,每个 MongoClient ,你可以使用 io.quarkus.mongodb.MongoClientName 修饰语选择要注入的客户端。使用上述属性来配置三个不同的客户端,你也可以按以下方式来注入每个客户端:

@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.0

如果你使用 开发服务 ,则不需要手动启动容器!

创建一个网页

现在让我们添加一个简单的网页来与我们的 FruitResource 进行交互。Quarkus会自动提供位于 META-INF/resources 目录下的静态资源。在 src/main/resources/META-INF/resources 目录中,添加一个 fruits.html 文件,其中包含这个 fruits.html 文件的内容。

现在你可以与你的REST服务进行交互:

  • 启动Quarkus:

    CLI
    quarkus dev
    Maven
    ./mvnw quarkus:dev
    Gradle
    ./gradlew --console=plain quarkusDev
  • 打开浏览器访问 <a href="http://localhost:8080/fruits.html" class="bare">http://localhost:8080/fruits.html</a>;

  • 通过表格添加新的fruits到列表中 :!devtools-wrapped:

响应式MongoDB客户端

Quarkus中包含一个响应式MongoDB客户端。使用它就像使用经典的MongoDB客户端一样简单。你可以重写前面的例子来使用它,如下所示:

弃用

io.quarkus.mongodb.ReactiveMongoClient 客户端已被废弃,并将在未来被删除。建议切换到提供 Mutiny API的 io.quarkus.mongodb.reactive.ReactiveMongoClient 客户端。

Mutiny

MongoDB的响应式客户端使用Mutiny响应式类型。如果你不熟悉Mutiny,请查看 Mutiny - 一个直观的响应式编程库

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 javax.enterprise.context.ApplicationScoped;
import javax.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 javax.inject.Inject;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.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编解码器简化MongoDB客户端的使用

通过使用Bson Codec ,MongoDB 客户端将自动处理您的域对象与 MongoDB Document 的相互转化。

首先你需要创建一个Bson Codec ,它将告诉Bson如何将你的实体与MongoDB Document 的相互转化。这里我们使用一个 CollectibleCodec ,因为我们的对象可以从数据库中检索到(它有一个MongoDB标识符),如果不是这样,我们会使用一个 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;
    }
}

然后你需要创建一个 CodecProvider 来把这个 Codec 链接到 Fruit 类。

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 bean。

最后,当从数据库中获取 MongoCollection 时,你可以直接使用 Fruit 类,而不是 Document ,编解码器会自动将 DocumentFruit 类相互映射(从 Fruit 类映射 Document 或者将 Document 映射到 Fruit 类)。

这是一个将 MongoCollectionFruitCodec 一起使用的示例。

package org.acme.mongodb;

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

import javax.enterprise.context.ApplicationScoped;
import javax.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编解码器

The POJO Codec provides a set of annotations that enable the customization of the way a POJO is mapped to a MongoDB collection and this codec is initialized automatically by Quarkus

其中一个注解是 @BsonDiscriminator ,它允许通过在文档中添加一个判别字段来在单个MongoDB集合中存储多个Java类型。在处理抽象类型或接口时,它可能很有用。

Quarkus 将使用 POJO codec自动注册所有使用 @BsonDiscriminator 的类。

POJO Codec通过 PropertyCodecProvider 增强了对泛型的支持,Quarkus会自动在POJO Codec中注册任何 PropertyCodecProvider (这些类会自动成为 @Singleton 范围的CDI bean)。当构建本地可执行文件和使用用泛型类型时,你可能需要用反射来注册类型参数。

用Panache简化MongoDB

MongoDB with Panache 扩展通过提供活动记录样式实体(和存储库)来促进 MongoDB 的使用,就像您在 Hibernate ORM with Panache 中所拥有的一样,并关注让你的实体在 Quarkus 中编写变得简单而有趣。

连接健康检查

如果你使用 quarkus-smallrye-health 扩展, quarkus-mongodb-client 将自动添加就绪状态检查,以验证与集群的连接。

因此,当你访问你的应用程序的 /q/health/ready 端点时,您将获得有关连接验证状态的信息。

可以通过在 application.properties 中将 quarkus.mongodb.health.enabled 属性设置为 false 来禁用此行为。

指标

如果你使用 quarkus-micrometerquarkus-smallrye-metrics 扩展, quarkus-mongodb-client 可以提供关于连接池的指标。这种行为必须首先通过在你的 application.properties 中设置 quarkus.mongodb.metrics.enabled 属性为 true 来启用。

因此,当你访问你的应用程序的 /q/metrics 端点时,你将得到有关连接池状态的信息。当使用 SmallRye Metrics 时,连接池指标将在 vendor 范围内可用。

跟踪

如果你使用 quarkus-smallrye-opentracing 扩展, quarkus-mongodb-client 可以注册关于所执行命令的跟踪。必须通过在你的 application.properties 中将 quarkus.mongodb.tracing.enabled 属性设置为 true 并在你的 pom.xml 中添加依赖性 io.opentracing.contrib:opentracing-mongo-common 来启用这一行为(更多信息请阅读 OpenTracing - MongoDB 客户端 部分)。

阅读 OpenTracing 指南,了解如何配置OpenTracing以及如何使用Jaeger追踪器。

测试助手

为了给你的单元测试启动MongoDB数据库,Quarkus提供了两个 QuarkusTestResourceLifecycleManager 依赖于 Flapdoodle嵌入式MongoDB

  • io.quarkus.test.mongodb.MongoTestResource 将在27017端口启动一个单一的实例。

  • io.quarkus.test.mongodb.MongoReplicaSetTestResource 将启动一个有两个实例的复制集,一个在27017端口,另一个在27018端口。

要使用它们,你需要在你的pom.xml中添加 io.quarkus:quarkus-test-mongodb 依赖。

有关 QuarkusTestResourceLifecycleManager 的更多信息,请阅读 Quarkus测试资源

旧客户端

我们默认不包括旧版的MongoDB客户端。它包含现已废弃的MongoDB Java API(DB、DBCollection…​…​)以及现已被 com.mongodb.client.MongoClient 所取代的 com.mongodb.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

然后你可以用常用的命令构建一个本地可执行文件:

CLI
quarkus build --native

+

Maven
./mvnw package -Dnative

+

Gradle
./gradlew build -Dquarkus.package.type=native

运行它就像执行 ./target/mongodb-quickstart-1.0.0-SNAPSHOT-runner 一样简单。

然后你可以使用的浏览器访问 <a href="http://localhost:8080/fruits.html" class="bare">http://localhost:8080/fruits.html</a>; 来使用你的应用程序。

目前,Quarkus在本地模式下不支持 客户端字段级加密

如果你在本地模式下运行你的应用程序时遇到以下错误。+ Failed to encode 'MyObject'. Encoding 'myVariable' errored with: Can’t find a codec for class org.acme.MyVariable. + 这意味着GeralVM不知道 org.acme.MyVariable 类,补救措施是将 @RegisterForReflection 注解添加到你的 MyVariable class 。关于 @RegisterForReflection 注解的更多细节可以在 本地应用程序提示 页面找到。

使用mongo+srv:// urls

mongo+srv:// urls在JVM模式下支持开箱即用。然而,在本地模式下,MongoDB客户端提供的默认DNS解析器使用的是JNDI,在本地模式下无法工作。

如果你需要在原生模式下使用 mongo+srv: ,你可以配置一个备用的DNS解析器。此功能是实验性的,可能会在 JVM 应用程序和本机应用程序之间产生差异。

要启用备用 DNS 解析器,请使用:

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

如属性名称所示,它使用 Vert.x 检索 DNS 记录。默认情况下,如果此文件存在,它会尝试从 etcresolv.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

配置参考

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

Configuration property

类型

默认

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

Environment variable: QUARKUS_MONGODB_HEALTH_ENABLED

boolean

true

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

Environment variable: QUARKUS_MONGODB_METRICS_ENABLED

boolean

false

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

Environment variable: QUARKUS_MONGODB_TRACING_ENABLED

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

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

boolean

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

Environment variable: QUARKUS_MONGODB_DEVSERVICES_IMAGE_NAME

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

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

string

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

Environment variable: QUARKUS_MONGODB_HOSTS

list of string

127.0.0.1:27017

Configure the database name.

Environment variable: QUARKUS_MONGODB_DATABASE

string

Configures the application name.

Environment variable: QUARKUS_MONGODB_APPLICATION_NAME

string

Configures the maximum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB_MAX_POOL_SIZE

int

Configures the minimum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB_MIN_POOL_SIZE

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

Duration

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

Environment variable: QUARKUS_MONGODB_MAX_CONNECTION_LIFE_TIME

Duration

Configures the time period between runs of the maintenance job.

Environment variable: QUARKUS_MONGODB_MAINTENANCE_FREQUENCY

Duration

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

Environment variable: QUARKUS_MONGODB_MAINTENANCE_INITIAL_DELAY

Duration

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

Environment variable: QUARKUS_MONGODB_CONNECT_TIMEOUT

Duration

How long a socket read can take before timing out.

Environment variable: QUARKUS_MONGODB_READ_TIMEOUT

Duration

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

Environment variable: QUARKUS_MONGODB_TLS_INSECURE

boolean

false

Whether to connect using TLS.

Environment variable: QUARKUS_MONGODB_TLS

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

string

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

Environment variable: QUARKUS_MONGODB_SERVER_SELECTION_TIMEOUT

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

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

Duration

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

Environment variable: QUARKUS_MONGODB_READ_CONCERN

string

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

Environment variable: QUARKUS_MONGODB_READ_PREFERENCE

string

The database used during the readiness health checks

Environment variable: QUARKUS_MONGODB_HEALTH_DATABASE

string

admin

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

boolean

false

If native.dns.use-vertx-dns-resolver is set to true, 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_NATIVE_DNS_SERVER_HOST

string

If native.dns.use-vertx-dns-resolver is set to true, this property configures the DNS server port. If not set, uses the system DNS resolver.

Environment variable: QUARKUS_MONGODB_NATIVE_DNS_SERVER_PORT

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_NATIVE_DNS_LOOKUP_TIMEOUT

Duration

5S

If native.dns.use-vertx-dns-resolver is set to true, this property enables the logging ot the DNS lookup. It can be useful to understand why the lookup fails.

Environment variable: QUARKUS_MONGODB_NATIVE_DNS_LOG_ACTIVITY

boolean

false

Generic properties that are added to the connection URL.

Environment variable: QUARKUS_MONGODB_DEVSERVICES_PROPERTIES

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

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

list of string

127.0.0.1:27017

Configure the database name.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__DATABASE

string

Configures the application name.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__APPLICATION_NAME

string

Configures the maximum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAX_POOL_SIZE

int

Configures the minimum number of connections in the connection pool.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MIN_POOL_SIZE

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

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

Duration

Configures the time period between runs of the maintenance job.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__MAINTENANCE_FREQUENCY

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

Duration

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

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CONNECT_TIMEOUT

Duration

How long a socket read can take before timing out.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__READ_TIMEOUT

Duration

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

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__TLS_INSECURE

boolean

false

Whether to connect using TLS.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__TLS

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

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

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

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

Duration

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

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__READ_CONCERN

string

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

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__READ_PREFERENCE

string

The database used during the readiness health checks

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__HEALTH_DATABASE

string

admin

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

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

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

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

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

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

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

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

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

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

Duration

Credentials and authentication mechanism

类型

默认

Configures the username.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_USERNAME

string

Configures the password.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_PASSWORD

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

string

Configures the source of the authentication credentials. This is typically the database that 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

string

Allows passing authentication mechanism properties.

Environment variable: QUARKUS_MONGODB_CREDENTIALS_AUTH_MECHANISM_PROPERTIES

Map<String,String>

Configures the username.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_USERNAME

string

Configures the password.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_PASSWORD

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

string

Configures the source of the authentication credentials. This is typically the database that 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

string

Allows passing authentication mechanism properties.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__CREDENTIALS_AUTH_MECHANISM_PROPERTIES

Map<String,String>

About the Duration format

持续时间的格式使用标准的 java.time.Duration 格式您可以在 Duration#parse() javadoc 中了解更多信息。

您还可以提供以数字开头的持续时间值。 在这种情况下,如果该值仅包含一个数字,则转换器将该值视为秒。 否则,PT 会隐式添加到值的前面,以获得标准的 java.time.Duration 格式。