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

Usando o cliente MongoDB

O MongoDB é um banco de dados NoSQL bem conhecido e amplamente utilizado.

Neste guia, veremos como você pode fazer com que seus serviços REST usem o banco de dados MongoDB.

Pré-requisitos

Para concluir este guia, você precisa:

  • Cerca de 15 minutos

  • Um IDE

  • JDK 17+ instalado com JAVA_HOME configurado corretamente

  • Apache Maven 3.9.6

  • Opcionalmente, o Quarkus CLI se você quiser usá-lo

  • Opcionalmente, Mandrel ou GraalVM instalado e configurado apropriadamente se você quiser criar um executável nativo (ou Docker se você usar uma compilação de contêiner nativo)

  • MongoDB instalado ou Docker instalado

Arquitetura

O aplicativo criado neste guia é bastante simples: o usuário pode adicionar elementos em uma lista usando um formulário e a lista é atualizada.

Todas as informações entre o navegador e o servidor são formatadas como JSON.

Os elementos são armazenados no MongoDB.

Solução

Recomendamos que siga as instruções nas seções seguintes e crie a aplicação passo a passo. No entanto, você pode ir diretamente para o exemplo completo.

Clone o repositório Git: git clone -b 3.8 https://github.com/quarkusio/quarkus-quickstarts.git, ou baixe um arquivo.

A solução está localizada no diretório mongodb-quickstart .

Criar o projeto Maven

Primeiro, precisamos de um novo projeto. Crie um novo projeto com o seguinte comando:

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

Para criar um projeto Gradle, adicione a opção --gradle ou --gradle-kotlin-dsl.

Para obter mais informações sobre como instalar e usar a CLI do Quarkus, consulte o guia Quarkus CLI.

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

Para criar um projeto Gradle, adicione a opção '-DbuildTool=gradle' ou '-DbuildTool=gradle-kotlin-dsl'.

Para usuários do Windows:

  • Se estiver usando cmd, (não use barra invertida '\' e coloque tudo na mesma linha)

  • Se estiver usando o Powershell, envolva os parâmetros '-D' entre aspas duplas, por exemplo, '"-DprojectArtifactId=mongodb-quickstart"'

Esse comando gera uma estrutura Maven importando as extensões RESTEasy Reactive Jackson e MongoDB Client. Depois disso, a extensão quarkus-mongodb-client foi adicionada ao seu arquivo de compilação.

Se já tiver o projeto Quarkus configurado, você pode adicionar a extensão mongodb-client ao projeto executando o seguinte comando no diretório base do projeto:

CLI
quarkus extension add mongodb-client
Maven
./mvnw quarkus:add-extension -Dextensions='mongodb-client'
Gradle
./gradlew addExtension --extensions='mongodb-client'

Isso adicionará o seguinte ao seu arquivo pom.xml:

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

Criando seu primeiro serviço JSON REST

Neste exemplo, criaremos um aplicativo para gerenciar uma lista de frutas.

Primeiro, vamos criar o bean Fruit da seguinte forma:

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;
    }
}

Nada de especial. Um aspecto importante a ser observado é que a camada de serialização JSON exige um construtor padrão.

Agora, crie um org.acme.mongodb.FruitService que será a camada de negócios do nosso aplicativo e armazene/carregue os frutos do banco de dados do 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");
    }
}

Agora, crie a classe org.acme.mongodb.FruitResource da seguinte forma:

@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();
    }
}

A implementação é bastante simples e você só precisa definir seus endpoints usando as anotações Jakarta REST e usar o FruitService para listar/adicionar novas frutas.

Configuração do banco de dados MongoDB

A principal propriedade a ser configurada é o URL para acessar o MongoDB. Quase todas as configurações podem ser incluídas no URI de conexão, por isso recomendamos que você faça isso. Você pode encontrar mais informações na documentação do MongoDB: https://docs.mongodb.com/manual/reference/connection-string/

Um exemplo de configuração deve ser semelhante a este:

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

Neste exemplo, estamos usando uma única instância em execução no localhost:

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

Se você precisar de mais propriedades de configuração, há uma lista completa no final deste guia.

Por padrão, o Quarkus restringirá o uso do JNDI em um aplicativo, como precaução para tentar mitigar quaisquer vulnerabilidades futuras semelhantes ao Log4Shell. Como o protocolo mongo+srv frequentemente usado para se conectar ao MongoDB requer JNDI, essa proteção é automaticamente desativada ao usar a extensão do cliente MongoDB.

Serviços de desenvolvimento (bancos de dados sem configuração)

O Quarkus oferece suporte a um recurso chamado Dev Services que permite que você crie várias fontes de dados sem nenhuma configuração. No caso do MongoDB, esse suporte se estende à conexão padrão do MongoDB. O que isso significa na prática é que, se você não tiver configurado quarkus.mongodb.connection-string , o Quarkus iniciará automaticamente um contêiner MongoDB ao executar testes ou no modo de desenvolvimento e configurará automaticamente a conexão.

O MongoDB Dev Services é baseado no módulo Testcontainers MongoDB que iniciará um conjunto de réplicas de nó único.

Ao executar a versão de produção do aplicativo, a conexão do MongoDB precisa ser configurada normalmente, portanto, se quiser incluir uma configuração de banco de dados de produção no seu application.properties e continuar a usar o Dev Services, recomendamos que use o perfil %prod. para definir as configurações do MongoDB.

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

Configuration property

Tipo

Padrão

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

booleano

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>

Vários clientes MongoDB

O MongoDB permite que você configure vários clientes. Usar vários clientes funciona da mesma forma que ter um único cliente.

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

Observe que há um bit extra na chave (os segmentos users e inventory ). A sintaxe é a seguinte: quarkus.mongodb.[optional name.][mongo connection property] . Se o nome for omitido, ele configurará o cliente padrão.

O uso de vários clientes do MongoDB possibilita o multilocatário para o MongoDB, permitindo a conexão a vários clusters do MongoDB. Se você quiser se conectar a vários bancos de dados dentro do mesmo cluster, não são necessários vários clientes, pois um único cliente é capaz de acessar todos os bancos de dados no mesmo cluster (como uma conexão JDBC é capaz de acessar vários esquemas dentro do mesmo banco de dados).

Injeção de cliente Mongo nomeado

Ao usar vários clientes, cada um MongoClient , você pode selecionar o cliente a ser injetado usando o qualificador io.quarkus.mongodb.MongoClientName . Usando as propriedades acima para configurar três clientes diferentes, você também pode injetar cada um deles da seguinte forma:

@Inject
MongoClient defaultMongoClient;

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

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

Executando um banco de dados MongoDB

Como, por padrão, o MongoClient está configurado para acessar um banco de dados local do MongoDB na porta 27017 (a porta padrão do MongoDB), se você tiver um banco de dados local em execução nessa porta, não há mais nada a fazer antes de poder testá-lo!

Se quiser usar o Docker para executar um banco de dados MongoDB, você pode usar o seguinte comando para iniciar um:

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

Se você usar o Dev Services , não será necessário iniciar o contêiner manualmente.

Criando um frontend

Agora vamos adicionar uma página da Web simples para interagir com o nosso site FruitResource . O Quarkus fornece automaticamente recursos estáticos localizados no diretório META-INF/resources . No diretório src/main/resources/META-INF/resources , adicione um arquivo fruits.html com o conteúdo desse arquivo fruits.html .

Agora você pode interagir com o serviço REST:

  • iniciar o Quarkus com:

    CLI
    quarkus dev
    Maven
    ./mvnw quarkus:dev
    Gradle
    ./gradlew --console=plain quarkusDev
  • abra um navegador para http://localhost:8080/fruits.html

  • adicionar novas frutas à lista por meio do formulário

Cliente MongoDB reativo

Um cliente MongoDB reativo está incluído no Quarkus. Usá-lo é tão fácil quanto usar o cliente MongoDB clássico. Você pode reescrever o exemplo anterior para usá-lo da seguinte forma.

Mutiny

O cliente reativo do MongoDB usa tipos reativos do Mutiny. Se você não estiver familiarizado com o Mutiny, consulte Mutiny - uma biblioteca de programação reativa intuitiva .

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);
    }
}

Simplificando o uso do cliente MongoDB usando o codec BSON

Ao usar um Bson Codec , o cliente MongoDB cuidará da transformação do seu objeto de domínio de/para um MongoDB Document automaticamente.

Primeiro, você precisa criar um Bson Codec que dirá ao Bson como transformar sua entidade de/para um MongoDB Document . Aqui usamos um CollectibleCodec porque nosso objeto pode ser recuperado do banco de dados (ele tem um identificador MongoDB); caso contrário, teríamos usado um Codec . Mais informações na documentação do codec: https://www.mongodb.com/docs/drivers/java/sync/current/fundamentals/data-formats/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;
    }
}

Em seguida, você precisa criar um CodecProvider para vincular esse Codec à classe 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;
    }

}

A Quarkus se encarrega de registrar o CodecProvider para você como um feijão CDI do escopo do @Singleton .

Por fim, ao obter o MongoCollection do banco de dados, você pode usar diretamente a classe Fruit em vez da Document . O codec mapeará automaticamente o Document para/de sua classe Fruit .

Aqui está um exemplo de uso de um MongoCollection com o FruitCodec .

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);
    }
}

O codec POJO

O codec POJO fornece um conjunto de anotações que permitem a personalização da maneira como um POJO é mapeado para uma coleção do MongoDB, e esse codec é inicializado automaticamente pelo Quarkus.

Uma dessas anotações é a anotação @BsonDiscriminator , que permite armazenar vários tipos Java em uma única coleção do MongoDB adicionando um campo discriminador dentro do documento. Isso pode ser útil ao trabalhar com tipos abstratos ou interfaces.

O Quarkus registrará automaticamente todas as classes anotadas com @BsonDiscriminator com o codec POJO.

O codec POJO tem suporte genérico aprimorado por meio de PropertyCodecProvider , o Quarkus registrará automaticamente qualquer PropertyCodecProvider com o codec POJO (essas classes são automaticamente transformadas em beans CDI do escopo @Singleton ). Ao criar executáveis nativos e usar tipos genéricos, talvez seja necessário registrar os argumentos do tipo para reflexão.

Simplificando o MongoDB com o Panache

A extensão MongoDB com Panache facilita o uso do MongoDB, fornecendo entidades (e repositórios) no estilo de registro ativo, como no Hibernate ORM com Panache , e se concentra em tornar as entidades triviais e divertidas de escrever no Quarkus.

Migração de esquemas com o Liquibase

A extensão Liquibase MongoDB facilita a inicialização de um banco de dados MongoDB, incluindo índices e dados iniciais. Ela implementa os mesmos recursos de migração de esquema que o Liquibase oferece para bancos de dados SQL.

Verificação da integridade da conexão

Se você estiver usando a extensão quarkus-smallrye-health , o quarkus-mongodb-client adicionará automaticamente uma verificação de integridade de prontidão para validar a conexão com o cluster.

Assim, quando você acessar o endpoint /q/health/ready do seu aplicativo, terá informações sobre o status de validação da conexão.

Esse comportamento pode ser desativado definindo a propriedade quarkus.mongodb.health.enabled como false em seu application.properties .

Métricas

Se você estiver usando a extensão quarkus-micrometer ou quarkus-smallrye-metrics , o quarkus-mongodb-client poderá fornecer métricas sobre os pools de conexão. Esse comportamento deve ser ativado primeiro definindo a propriedade quarkus.mongodb.metrics.enabled como true em seu application.properties .

Assim, quando você acessar o endpoint /q/metrics do seu aplicativo, terá informações sobre o status do pool de conexões. Ao usar o SmallRye Metrics , as métricas do pool de conexões estarão disponíveis no escopo vendor .

Ajudantes de teste

O Dev Services for MongoDB é a melhor opção para iniciar um banco de dados MongoDB para seus testes de unidade.

Mas se não puder usá-lo, você pode iniciar um banco de dados MongoDB usando um dos dois QuarkusTestResourceLifecycleManager que o Quarkus fornece. Eles dependem do MongoDB incorporado ao Flapdoodle .

  • io.quarkus.test.mongodb.MongoTestResource iniciará uma única instância na porta 27017.

  • io.quarkus.test.mongodb.MongoReplicaSetTestResource iniciará um conjunto de réplicas com duas instâncias, uma na porta 27017 e a outra na porta 27018.

Para usá-los, você precisa adicionar a dependência io.quarkus:quarkus-test-mongodb ao seu pom.xml.

Para obter mais informações sobre o uso do site QuarkusTestResourceLifecycleManager , leia o recurso de teste do Quarkus .

Para definir a porta desejada que o MongoDB escutará quando for iniciado, o código a seguir deve ser usado:

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

Para definir a versão desejada do MongoDB que será iniciada, o código a seguir deve ser usado:

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

O valor da cadeia de caracteres usado pode ser qualquer um dos enums de.flapdoodle.embed.mongo.distribution.Version ou de.flapdoodle.embed.mongo.distribution.Version.Main . Se nenhuma versão for especificada, Version.Main.V4_0 será usado por padrão.

O cliente antigo

Por padrão, não incluímos o cliente MongoDB legado. Ele contém a API Java do MongoDB (DB, DBCollection,…​), agora aposentada, e o site com.mongodb.MongoClient , que agora foi substituído pelo site com.mongodb.client.MongoClient .

Se quiser usar a API herdada, você precisará adicionar a seguinte dependência ao seu arquivo de compilação:

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

Criação de um executável nativo

Você pode usar o cliente MongoDB em um executável nativo.

Se quiser usar a criptografia SSL/TLS, você precisa adicionar essas propriedades no site application.properties :

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

Em seguida, você pode criar um executável nativo com o comando usual:

CLI
quarkus build --native
Maven
./mvnw install -Dnative
Gradle
./gradlew build -Dquarkus.package.type=native

Para executá-lo, basta acessar ./target/mongodb-quickstart-1.0.0-SNAPSHOT-runner .

Em seguida, você pode direcionar seu navegador para http://localhost:8080/fruits.html e usar seu aplicativo.

Atualmente, o Quarkus não suporta Client-Side Field Level Encryption no modo nativo.

Se você encontrar o seguinte erro ao executar seu aplicativo no modo nativo: Failed to encode 'MyObject'. Encoding 'myVariable' errored with: Can’t find a codec for class org.acme.MyVariable. Isso significa que a classe org.acme.MyVariable não é conhecida pelo GraalVM. A solução é adicionar a anotação @RegisterForReflection ao seu aplicativo MyVariable class . Mais detalhes sobre a anotação @RegisterForReflection podem ser encontrados na página de dicas de aplicativos nativos .

Usando urls mongo+srv://

mongo+srv:// são suportados imediatamente no modo JVM. No entanto, no modo nativo, o resolvedor de DNS padrão, fornecido pelo cliente MongoDB, usa JNDI e não funciona no modo nativo.

Se precisar usar o mongo+srv:// no modo nativo, você pode configurar um resolvedor de DNS alternativo. Esse recurso é experimental e pode introduzir uma diferença entre os aplicativos JVM e os aplicativos nativos.

Para ativar o resolvedor de DNS alternativo, use:

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

Conforme indicado no nome da propriedade, ele usa Vert.x para recuperar os registros DNS. Por padrão, ele tenta ler o primeiro nameserver de /etc/resolv.conf , se esse arquivo existir. Você também pode configurar seu servidor 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

Além disso, você pode configurar o tempo limite de pesquisa usando:

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

Personalizar a configuração do cliente Mongo de forma programática

Se precisar personalizar a configuração do cliente Mongo de forma programática, você precisará implementar a interface io.quarkus.mongodb.runtime.MongoClientCustomizer e expô-la como um bean com escopo de aplicativo CDI:

@ApplicationScoped
public class MyCustomizer implements MongoClientCustomizer {

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

O bean pode personalizar um cliente específico usando o qualificador @MongoClientName para indicar o nome do cliente. Quando não há qualificador, ele personaliza o cliente padrão. No máximo um personalizador pode ser usado por cliente. Se forem detectados vários personalizadores direcionados ao mesmo cliente, será lançada uma exceção no momento da compilação.

Esse recurso pode ser usado para configurar a criptografia de nível de campo no lado do cliente (CSFLE). Siga as instruções do site da Mongo para configurar o 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());
    }
}
A criptografia em nível de campo do lado do cliente e os recursos que dependem do Mongo Crypt em geral não são compatíveis com o modo nativo.

Referência de configuração

Propriedade de Configuração Fixa no Momento da Compilação - Todas as outras propriedades de configuração podem ser sobrepostas em tempo de execução.

Configuration property

Tipo

Padrão

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

Environment variable: QUARKUS_MONGODB_HEALTH_ENABLED

Show more

booleano

true

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

Environment variable: QUARKUS_MONGODB_METRICS_ENABLED

Show more

booleano

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

booleano

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

booleano

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

booleano

false

Whether to connect using TLS.

Environment variable: QUARKUS_MONGODB_TLS

Show more

booleano

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

booleano

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

booleano

false

Whether to connect using TLS.

Environment variable: QUARKUS_MONGODB__MONGO_CLIENT_CONFIGS__TLS

Show more

booleano

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

Tipo

Padrão

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

booleano

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

booleano

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

booleano

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

booleano

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

booleano

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

booleano

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

Tipo

Padrão

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

About the Duration format

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

Você também pode usar um formato simplificado, começando com um número:

  • Se o valor for apenas um número, ele representará o tempo em segundos.

  • Se o valor for um número seguido de 'ms', ele representa o tempo em milissegundos.

Em outros casos, o formato simplificado é traduzido para o formato 'java.time.Duration' para análise:

  • Se o valor for um número seguido de 'h', 'm' ou 's', ele é prefixado com 'PT'.

  • Se o valor for um número seguido de 'd', ele é prefixado com 'P'.

Related content