Visão geral
Esta seção descreve as opções de conexão e autenticação do MongoDB disponíveis no driver Rust. Você pode configurar sua conexão usando o URI de conexão (também chamada de string de conexão) ou definindo campos em uma ClientOptions instância ao criar Client um.
Como utilizar o URI de conexão
Se você passar um URI de conexão para o método Client::with_uri_str, poderá incluir opções de conexão na cadeia de caracteres como pares <name>=<value>. O exemplo a seguir mostra um URI de conexão contendo a opção connectTimeoutMS com um valor de 60000 e a opção tls com um valor de true:
use mongodb::Client; let uri = "mongodb://<hostname>:<port>/?connectTimeoutMS=60000&tls=true"; let client = Client::with_uri_str(uri).await?;
Uso do ClientOptions
Você pode definir opções de conexão em uma instância ClientOptions em vez de incluí-las no URI de conexão. Ao configurar sua conexão usando uma instância do ClientOptions, é mais fácil alterar as configurações no tempo de execução e detectar erros durante a compilação. O exemplo seguinte mostra como utilizar o ClientOptions para configurar opções de conexão:
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)?;
Opções de conexão
As seções a seguir descrevem as opções de conexão disponíveis no driver Rust. Para ver uma lista completa de opções de conexão, visite a seção Opções de connection string do guia manual do servidor sobre connection strings.
Compactação de rede
Nome da opção | Valores aceitos | Valor padrão | Descrição |
|---|---|---|---|
compressors | Uma lista de strings separadas por vírgula | none | Specifies compressors that the Client instance uses in
the specified order.To learn more about network compression, see the
Network Compression guide. |
zlibCompressionLevel | Inteiro 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. |
Tempo-limite
Nome da opção | Valores aceitos | Valor padrão | Descrição |
|---|---|---|---|
connectTimeoutMS | Non-negative integer |
| Especifica o tempo limite de conexão, em milissegundos, passado para cada fluxo TCP subjacente ao tentar se conectar ao servidor. |
Seleção do Servidor
Nome da opção | Valores aceitos | Valor padrão | Descrição |
|---|---|---|---|
heartbeatFrequencyMS | inteiro maior ou igual a 500 |
| Especifica a quantidade de tempo, em milésimos de segundo, que cada thread de monitoramento aguarda entre as verificações do 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 a quantidade de tempo, em milésimos de segundo, que a instância |
Autenticação
Nome da opção | Valores aceitos | Valor padrão | Descrição |
|---|---|---|---|
authMechanism | String | none | Especifica qual mecanismo de autenticação usar. Se você não especificar esta opção, o driver usará o mecanismo de autenticação padrão. Para saber mais sobre autenticação no driver Rust, consulte o guia sobre mecanismos de autenticação. |
authMechanismProperties | String | none | Especifica mais propriedades para o mecanismo de autenticação definido na opção |
authSource | String | Veja a descrição | 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 | Boolean |
| Specifies the TLS configuration for the Client instance
to use in its connections with the server.By default, TLS is off. |
tlsAllowInvalidCertificates | Boolean |
| 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 | Veja a descrição | 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 | none | 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 | none | Especifica a senha para descriptografar a chave privada em seu arquivo de certificado, se a chave estiver criptografada. |
tlsInsecure | Boolean |
| 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. |
Operações de leitura e escrita
Nome da opção | Valores aceitos | Valor padrão | Descrição |
|---|---|---|---|
directConnection | Boolean |
| Especifica se a instância do |
journal | Boolean |
| Solicita confirmação de que a operação foi propagada para o diário em 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. |
readConcernLevel | String | none | 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 | Uma lista de pares de valores-chave separados por vírgula | none | 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 | none | Especifica o nome do conjunto de réplicas ao qual a instância |
retryReads | Boolean |
| Especifica se o cliente tenta novamente uma operação de leitura se a operação falhar. |
w | inteiro ou string não negativo | none | 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 | Sem tempo limite | 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. |
Pool de Conexões
Nome da opção | Valores aceitos | Valor padrão | Descrição |
|---|---|---|---|
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 obter mais informações sobre pools de conexões, consulte o guia pools de conexões.
Em geral
Nome da opção | Valores aceitos | Valor padrão | Descrição |
|---|---|---|---|
appName | String | none | 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. |
Documentação da API
Para obter mais informações sobre ClientOptions para o driver Rust, consulte a documentação da API para ClientOptions.