Overview
Esta sección describe las opciones de conexión y autenticación de MongoDB disponibles en el controlador de sincronización de Kotlin. Puede configurar su conexión configurando las opciones en la URI de conexión o dentro de un
MongoClientSettings instancia.
Establecer opciones en la URI de conexión
Si pasa una URI de conexión al método MongoClient.create(), puede incluir opciones de conexión en la cadena como pares <name>=<value>. En el siguiente ejemplo, la URI de conexión contiene la opción connectTimeoutMS con un valor de 60000 y la opción tls con un valor de true:
val uri = "mongodb://<hostname>:<port>/?connectTimeoutMS=60000&tls=true" val mongoClient = MongoClient.create(uri)
Establecer opciones en MongoClientSettings
Puede establecer opciones de conexión en una instancia MongoClientSettings utilizando métodos de la clase MongoClientSettings.Builder y luego pasando el objeto de configuración al método MongoClient.create().
Configurar la conexión de esta manera facilita el cambio de configuraciones en tiempo de ejecución y puede ayudarle a detectar errores en tiempo de compilación.
El siguiente ejemplo muestra cómo especificar el destino de conexión y ajustar otras opciones al crear una instancia de MongoClientSettings:
val settings = MongoClientSettings.builder() .applyToClusterSettings { builder -> builder.hosts(listOf(ServerAddress("localhost", 27017))) } .applyToSocketSettings { builder -> builder.connectTimeout(60000, TimeUnit.MILLISECONDS) } .applyToSslSettings { builder -> builder.enabled(true) } .build() val mongoClient = MongoClient.create(settings)
Si prefiere proporcionar una cadena de conexión en lugar de especificar el nombre de host y el puerto, puede usar el método applyConnectionString() y luego configurar otras opciones mediante los métodos del generador, como se muestra en el siguiente código:
val uri = "<connection string>" val settings = MongoClientSettings.builder() .applyConnectionString(ConnectionString(uri)) .applyToSocketSettings { builder -> builder.connectTimeout(60000, TimeUnit.MILLISECONDS) } .applyToSslSettings { builder -> builder.enabled(true) } .build() val mongoClient = MongoClient.create(settings)
Opciones de conexión
Las siguientes secciones describen las opciones de conexión disponibles en el controlador de sincronización de Kotlin. Cada opción muestra el par opción-valor que se puede usar en una URI de conexión y, si está disponible, el método del controlador para configurarlo en una instancia MongoClientSettings.
Compresión de la red
Opción de conexión | Descripción |
|---|---|
compresores | The preferred compression types, in order, for wire-protocol messages sent to
or received from the server. The driver uses the first of these compression types
that the server supports. Data Type: comma-delimited string MongoClientSettings: compressorList(listOf(<MongoCompressor>))Connection URI: compressors=snappy,zstd,zlib |
zlibCompressionLevel | The compression level for zlib to use. This option accepts
an integer value between -1 and 9, corresponding to the
following settings:- -1: (Default). zlib uses its default compression level (usually 6).- 0: No compression. - 1: Fastest speed but lowest compression. - 9: Best compression but slowest speed. Data Type: integer Default: -1MongoClientSettings: compressorList(listOf(zlib.withProperty(MongoCompressor.LEVEL, 3)))Connection URI: zlibCompressionLevel=3 |
Tiempos de espera
Opción de conexión | Descripción | |||
|---|---|---|---|---|
connectTimeoutMS | The time in milliseconds to attempt a connection before timing out. Data Type: integer Default: 10000MongoClientSettings: Connection URI: timeoutMs=10000 | |||
socketTimeoutMS (deprecated) | This option is deprecated. You can configure this timeout by setting the the client-level timeout instead. Milliseconds to attempt a send or receive on a connection before the attempt times out. Data Type: integer Default: no timeout MongoClientSettings: Connection URI: socketTimeoutMS=5000 |
Selección de servidores
Opción de conexión | Descripción | |||
|---|---|---|---|---|
Tiempo de espera de selección del servidor MS | The maximum amount of time, in milliseconds, the driver waits
for server selection to succeed before throwing an
exception. Data Type: integer Default: 30000MongoClientSettings: Connection URI: serverSelectionTimeoutMS=30000 |
Autenticación
Tip
Para obtener más información sobre las opciones de autenticación, consulte la sección Mecanismos de autenticación.
Opción de conexión | Descripción | |||
|---|---|---|---|---|
mecanismo de autenticación | The mechanism that the Kotlin Sync driver uses to authenticate
the application. Data Type: string Default: "SCRAM-SHA-256" when connecting to MongoDB
v4.0 or laterMongoClientSettings: Connection URI: authMechanism=SCRAM-SHA-256 | |||
Propiedades del mecanismo de autenticación | Options specific to the authentication mechanism. This option
isn't needed for all authentication mechanisms. Data Type: string Connection URI: authMechanismProperties=AWS_SESSION_TOKEN:12435 | |||
authSource | The database to authenticate against. Data Type: string Default: "admin"Connection URI: authSource=admin | |||
Nombre de usuario | The username for authentication. When this option is included in a connection
URI, you must percent-encode it. Data Type: string Connection URI: username=my+user | |||
contraseña | The password for authentication. When this option is included in a connection
URI, you must percent-encode it. Data Type: string Connection URI: password=strong+password |
Operaciones de lectura y escritura
Para obtener más información sobre cómo conectar con diferentes tipos de implementaciones de MongoDB, consulta la guía Elige un Target de Conexión.
Opción de conexión | Descripción | |||
|---|---|---|---|---|
replicaSet | Specifies the name of the replica set to connect to. Data Type: string Connection URI: replicaSet=myRS | |||
directConnection | Whether to connect only to the primary member of the replica set. Data Type: boolean Default: falseMongoClientSettings: Connection URI: directConnection=true | |||
readPreference | Specifies the client's read preference. For more information,
see Read Preference in the
Server manual. Data Type: string Default: primaryMongoClientSettings: readPreference(ReadPreference.primary())Connection URI: readPreference=primary | |||
readConcern | Specifies the client's read concern. For more information, see
Read Concern in the Server
manual. Data Type: string MongoClientSettings: readConcern(ReadConcern.MAJORITY)Connection URI: readConcern=majority | |||
writeConcern | Specifies the client's write concern. For more information, see
Write Concern in the
Server manual. Data Type: string MongoClientSettings: writeConcern(WriteConcern.MAJORITY)Connection URI: writeConcern=majority | |||
localThresholdMS | The latency window for a replica-set member's eligibility. If a member's
round trip ping takes longer than the fastest server's round-trip ping
time plus this value, the server isn't eligible for selection. Data Type: integer Default: 15MongoClientSettings: Connection URI: localThresholdMS=35 |
Información Adicional
Para ver una lista completa de opciones de conexión, consulte Cadenas de conexión en el manual del servidor.
Documentación de la API
Para obtener más información sobre las clases y los métodos mencionados en esta guía, consulte la siguiente documentación de API: