Overview
Esta sección describe las opciones de conexión y autenticación de MongoDB disponibles en el driver de Rust. Puedes configurar tu conexión utilizando la URI de conexión (también llamada cadena de conexión) o estableciendo campos en un ClientOptions instancia cuando creas un Client.
Uso del URI de conexión
Si pasas un URI de conexión al Client::with_uri_str método, puedes incluir opciones de conexión en la string como pares <name>=<value>. El siguiente ejemplo muestra un URI de conexión que contiene la opción connectTimeoutMS con un valor de 60000 y la opción tls con un valor de true:
use mongodb::Client; let uri = "mongodb://<hostname>:<port>/?connectTimeoutMS=60000&tls=true"; let client = Client::with_uri_str(uri).await?;
Uso de ClientOptions
Puede configurar las opciones de conexión en una instancia de ClientOptions en lugar de incluirlas en tu URI de conexión. Cuando configuras tu conexión usando una instancia de ClientOptions, es más fácil cambiar la configuración en tiempo de ejecución y detectar errores durante la compilación. El siguiente ejemplo muestra cómo utilizar ClientOptions para configurar las opciones de conexión:
use std::time::Duration; use mongodb::{Client, options::ClientOptions}; let uri = "mongodb://<hostname>:<port>/"; let mut client_options = ClientOptions::parse(uri).await?; client_options.connect_timeout = Some(Duration::from_secs(60000)); //Set additional options on client_options here let client = Client::with_options(client_options)?;
Opciones de conexión
Las siguientes secciones describen las opciones de conexión disponibles en el controlador Rust. Para ver una lista completa de las opciones de conexión, visite la sección Opciones de Cadena de Conexión de la guía manual del Servidor sobre Cadenas de Conexión.
Compresión de la red
Nombre de la opción | Valores permitidos | Valor por defecto | Descripción |
|---|---|---|---|
compresores | Una lista de cadenas separadas por comas | Ninguno | Specifies compressors that the Client instance uses in
the specified order.To learn more about network compression, see the
Network Compression guide. |
zlibCompressionLevel | Número entero entre |
| Specifies the level field of the zlib compression if you
use that compressor. A higher level value results in more
compression, which is slower.Setting a value of 0 specifies no compression, and
setting a value of 9 specifies maximum compression.To learn more about network compression, see the
Network Compression guide. |
Tiempo de espera
Nombre de la opción | Valores permitidos | Valor por defecto | Descripción |
|---|---|---|---|
connectTimeoutMS | Non-negative integer |
| Especifica el tiempo de espera de conexión, en milisegundos, que se pasa a cada flujo TCP subyacente al intentar conectarse al servidor. |
Selección de servidores
Nombre de la opción | Valores permitidos | Valor por defecto | Descripción |
|---|---|---|---|
heartbeatFrequencyMS | entero mayor o igual a 500 |
| Especifica la cantidad de tiempo en milisegundos que cada hilo de supervisión espera entre ejecuciones de pruebas al servidor. |
maxStalenessSeconds |
|
| Specifies the maximum lag, in seconds, behind the primary
node that a secondary node can be considered for the given
operation. The value of this option must be at least 90, or the
operation raises an error. A value of -1 means there is
no maximum lag. |
serverSelectionTimeoutMS | Non-negative integer |
| Especifica la cantidad de tiempo en milisegundos que la instancia |
Autenticación
Nombre de la opción | Valores permitidos | Valor por defecto | Descripción |
|---|---|---|---|
mecanismo de autenticación | String | Ninguno | Especifica qué mecanismo de autenticación utilizar. Si no especifica esta opción, el driver utilizará el mecanismo de autenticación por defecto. Para obtener más información sobre la autenticación en el driver Rust, consulta la guía sobre mecanismos de autenticación. |
authMechanismProperties | String | Ninguno | Especifica más propiedades para el mecanismo de autenticación establecido en la opción |
authSource | String | Ver descripción | Specifies the database used to authenticate. This option defaults to admin for SCRAM-based
authentication mechanisms, $external for the
MONGODB-X509 mechanism, and the database name or
$external for the PLAIN mechanism. |
tls | Booleano |
| Specifies the TLS configuration for the Client instance
to use in its connections with the server.By default, TLS is off. |
tlsPermitirCertificadosInválidos | Booleano |
| Specifies whether the Client instance returns an error if the
server presents an invalid certificate.We recommend that you set this option to true only in
testing environments to avoid creating vulnerabilities in your
application. |
tlsCAFile | String | Ver descripción | Specifies the path to the certificate authority (CA) file that
the Client instance uses for TLS.If you do not specify this option, the driver uses the Mozilla
root certificates from the webpki-roots crate. |
tlsCertificateKeyFile | String | Ninguno | Specifies the path to the certificate file that the Client
instance presents to the server to verify its identify.If you do not set this option, the Client instance does not
attempt to verify its identity to the server. |
tlsCertificateKeyFilePassword | String | Ninguno | Especifica la contraseña para descifrar la llave privada en tu archivo de certificado, en caso de que la clave esté cifrada. |
tlsInsecure | Booleano |
| Specifies whether the Client instance returns an error if the
server presents an invalid certificate.We recommend that you set this option to true only in
testing environments to avoid creating vulnerabilities in your
application. |
Operaciones de Lectura y Escritura
Nombre de la opción | Valores permitidos | Valor por defecto | Descripción |
|---|---|---|---|
directConnection | Booleano |
| Especifica si la instancia |
enableOverloadRetargeting | Booleano |
| Especifica si el controlador da menos prioridad a un servidor que devuelve un error de sobrecarga, reduciendo la probabilidad de reintentos en el mismo servidor sobrecargado. |
journal | Booleano |
| Solicita confirmación de que la operación se propagó al registro en disco. |
localThresholdMS | Non-negative integer |
| Specifies the amount of time in milliseconds that the average
round-trip time between the driver and server can last
compared to the shortest round-trip time of all the suitable
servers. A value of 0 indicates that there is no latency window,
so only the server with the lowest average round-trip time
is eligible. |
maxAdaptiveRetries | Non-negative integer |
| Especifica el número máximo de reintentos que se debe realizar cuando el controlador se enfrenta a errores de sobrecarga. |
readConcernLevel | String | Ninguno | Specifies the default read concern for operations performed
on the Client instance.To learn more, see Read Concern in the Server manual. |
readPreference | String |
| Specifies how the driver routes a read operation to members
of a replica set. To learn more, see Read Preference in the Server manual. |
readPreferenceTags | Una lista de pares de clave-valor separados por comas | Ninguno | Specifies which replica set members are considered for
operations. Each instance of this key is a separate tag set. The driver checks each tag set until it finds one or more
servers with each tag in the set. |
replicaSet | String | Ninguno | Especifica el nombre del set de réplicas al que se conecta la instancia |
retryReads | Booleano |
| Especifica si el cliente reintenta una operación de lectura si la operación falla. |
w | Entero no negativo o string | Ninguno | Requests acknowledgment that the operation has propagated to a
specific number or variety of servers. To learn more, see Write Concern in the Server manual. |
wTimeoutMS | Non-negative integer | Sin límite de tiempo | Specifies a time limit, in milliseconds, for the write
concern. If an operation has not propagated to the requested level
within the time limit, the driver raises an error. |
Pools de conexiones
Nombre de la opción | Valores permitidos | Valor por defecto | Descripción |
|---|---|---|---|
maxIdleTimeMS | Non-negative integer |
| Specifies the amount of time in milliseconds that a
connection can remain idle in a connection pool before the
server closes it. A value of 0 indicates that the client does not close
idle connections. |
maxPoolSize | Non-negative integer |
| Specifies the maximum number of connections that the
Client instance can create in a connection pool for a
given server.If you attempt an operation while the value of
maxPoolSize connections are checked out, the operation
waits until an in-progress operation finishes and the
connection returns to the pool. |
minPoolSize | Non-negative integer |
| Specifies the minimum number of connections available in a
server's connection pool at a given time. If fewer than minPoolSize connections are in the pool,
the server adds connections in the background up to the
value of minPoolSize. |
Para obtener más información sobre los pool de conexiones, consulta la guía de pool de conexiones.
General
Nombre de la opción | Valores permitidos | Valor por defecto | Descripción |
|---|---|---|---|
appName | String | Ninguno | Specifies the application name that the Client instance
sends to the server as part of the handshake.Specifying an appName can help you use the server logs
to determine which Client instance is connected to the
server. |
Documentación de la API
Para obtener más información sobre ClientOptions para el driver de Rust, consulta la documentación de la API para ClientOptions.