Overview
Esta sección describe las opciones de conexión y autenticación de MongoDB que puede pasar como parámetros del URI de conexión en el controlador Java Reactive Streams.
Uso de la URI de conexión
Si pasa una URI de conexión a la MongoClient En el constructor, puede incluir opciones de conexión en la cadena como pares <name>=<value>. En el siguiente ejemplo, el URI de conexión contiene la opción connectTimeoutMS con un valor de 60000 y la opción tls con un valor de true:
public class MongoConnection { public static void main(String[] args) { String uri = "mongodb://<hostname>:<port>/?connectTimeoutMS=60000&tls=true"; try (MongoClient client = MongoClients.create(uri)) { // Use client here } } }
Opciones de conexión
Las siguientes secciones describen las opciones de conexión disponibles en el controlador Java Reactive Streams. Puede pasar estas opciones como parámetros del URI de conexión para especificar el comportamiento del cliente.
Autenticación
Opción de conexión | Descripción |
|---|---|
mecanismo de autenticación | Sets the mechanism the Java Reactive Streams driver uses to authenticate the application. Valid options are defined in the Class ConnectionString API documentation. Data Type: StringDefault: "SCRAM-SHA-256" when connecting to MongoDB v4.0 or later."SCRAM-SHA-1" when connecting to MongoDB v3.0 through v3.13.Connection URI Example: authMechanism=MONGODB-X509 |
Propiedades del mecanismo de autenticación | Sets options specific to the authentication mechanism. Data Type: StringDefault: ""Connection URI Example: authMechanismProperties=AWS_SESSION_TOKEN:12435 |
authSource | Sets the source of authentication credentials. The source is typically a database. This option is only respected when authMechanism is setto MONGO-CR.Data Type: StringDefault: The database in the connection URI, or "admin" if none is providedConnection URI Example: authSource=admin |
Nombre de usuario | Sets the username for authentication. When this option is included in a connection URI, you must percent-escape it. Data Type: StringDefault: ""Connection URI Example: username=my+user |
contraseña | Sets the password for authentication. When this option is included in a connection URI, you must percent-escape it. Data Type: StringDefault: ""Connection URI Example: password=strong+password |
Configuración de la conexión
Opción de conexión | Descripción |
|---|---|
connectTimeoutMS | Sets the number of milliseconds the connection can take before timing out. If an operation doesn't finish in the specified time, the Java Reactive Streams driver raises a timeout exception. Data Type: IntegerDefault: nullConnection URI Example: connectTimeoutMS=6000 |
maxIdleTimeMS | Sets the maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. Set this value higher than your application's expected idle period but lower than firewall or proxy connection timeouts to prevent unexpected disconnections. Data Type: IntegerDefault: nullConnection URI Example: maxIdleTimeMS=6000 |
Tiempo de vida máximo MS | Sets the maximum lifetime in milliseconds of a pooled connection. If an operation doesn't finish in the specified time, the Java Reactive Streams driver closes the connection. Data Type: IntegerDefault: nullConnection URI Example: maxLifeTimeMS=6000 |
socketTimeoutMS (deprecated) | This option is deprecated. You can configure this timeout by setting the the client-level timeout instead. Milliseconds a receive on a socket can take before timing out. If an operation doesn't finish in the specified time, the Java Reactive Streams driver raises a timeout exception. Data Type: IntegerDefault: nullConnection URI Example: socketTimeoutMS=6000 |
ssl | Sets whether to connect using TLS/SSL. Data Type: booleanDefault: nullConnection URI Example: ssl=true |
sslNombre de host no válido permitido | Allows invalid host names for TLS/SSL connections. Data Type: booleanDefault: nullConnection URI Example: sslInvalidHostNameAllowed=true |
tls | Sets whether to connect using TLS. Supersedes the ssl option.Data Type: booleanDefault: nullConnection URI Example: tls=true |
tlsPermitir nombres de host no válidos | Allows invalid host names for TLS connections. Supersedes the sslInvalidHostNameAllowed option.Data Type: booleanDefault: nullConnection URI Example: tlsAllowInvalidHostnames=true |
tlsInsecure | Enables insecure TLS connections when connecting using TLS. Data Type: booleanDefault: nullConnection URI Example: tlsInsecure=true |
Configuración del grupo de conexiones
Opción de conexión | Descripción |
|---|---|
maxConnecting | Sets the maximum number of connections a pool can establish concurrently. Data Type: IntegerDefault: nullConnection URI Example: maxConnecting=5 |
maxPoolSize | Sets the maximum number of connections in the connection pool.
If an operation needs a new connection while the connection pool has
maxPoolSize connections open, the new operation waits for a
new connection to open. To limit this waiting time, use the
single timeout setting. To learn more, see the
Limit Server Execution Time guide.Data Type: IntegerDefault: nullConnection URI Example: maxPoolSize=5 |
minPoolSize | Sets the minimum number of connections in the connection pool. Data Type: IntegerDefault: nullConnection URI Example: minPoolSize=3 |
waitQueueTimeoutMS (deprecated) | This option is deprecated. You can configure this timeout by setting the the client-level timeout instead. Maximum amount of time to wait in milliseconds before either an in-use connection becomes available or a connection is created and starts becoming established. Data Type: IntegerDefault: nullConnection URI Example: waitQueueTimeoutMS=6000 |
Configuración del compresor
Opción de conexión | Descripción |
|---|---|
compresores | Sets preferred compression types, in order, for wire-protocol messages sent to or received from the server. Compression types must be passed in as a comma-separated list. The driver uses the first of these compression types that the server supports. Data Type: StringDefault: nullConnection URI Example: compressors=snappy,zstd,zlib |
zlibCompressionLevel | Sets the compression level for zlib to use. This option accepts an integer value between -1 and 9:- -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: IntegerDefault: -1Connection URI Example: zLibCompressionLevel=3 |
Configuración general
Opción de conexión | Descripción |
|---|---|
directConnection | Sets whether the driver connects directly to the host. Data Type: booleanDefault: nullConnection URI Example: directConnection=true |
loadBalanced | Sets whether or not the driver is connecting to MongoDB using a load balancer. If true, the driver assumes that it is connecting through aload balancer. Data Type: booleanDefault: nullConnection URI Example: directConnection=true |
retryWrites | Sets whether or not the driver retries supported write operations if they fail due to a network error. Data Type: booleanDefault: TrueConnection URI Example: retryWrites=true |
retryReads | Sets whether or not the driver retries supported read operations if they fail due to a network error. Data Type: booleanDefault: TrueConnection URI Example: retryReads=true |
Representación uuid | Sets the mechanism the Java Reactive Streams driver uses to encode instances of UUID. See the Uuid Representation API documentation for a list of all valid options. Data Type: StringDefault: unspecifiedConnection URI Example: uuidRepresentation=unspecified |
Configuración de proxy
Opción de conexión | Descripción |
|---|---|
proxyHost | Establishes the SOCKS5 proxy host to establish a connection through. The value of the proxyHost can be a valid IPv4 address, IPv6address, or a domain name. Required if either proxyPassword, proxyUsername or proxyPort are specified.Data Type: StringDefault: nullConnection URI Example: proxyHost=example.com |
proxyPort | Sets the port number for the SOCKS5 proxy server. Must be a non-negative integer. Data Type: IntegerDefault: nullConnection URI Example: proxyPort=27 |
proxyUsername | Sets the username for authenticating with the proxy server. Required if proxyPassword is specified.Data Type: StringDefault: nullConnection URI Example: proxyUsername=example |
proxyPassword | Sets the password for authenticating with the proxy server. Required if proxyPassword is specified.Data Type: StringDefault: nullConnection URI Example: proxyPassword=password |
Configuración de preferencias de lectura
Opción de conexión | Descripción |
|---|---|
readPreference | Sets the read preference for this connection. Enumerated values are: primary, primaryPreferred, secondary, secondaryPreferred, and nearest.Data Type: EnumDefault: primaryConnection URI Example: readPreference.primary |
readPreferenceTags | Specifies a tag set as a comma-separated list of colon-separated key-value pairs, e.g. dc:ny,rack:1.Spaces are stripped from beginning and end of all keys and values. To specify a list of tag sets, use multiple readPreferenceTags, separatedby semicolons. To learn more about readPreferenceTags, see the Class ConnectionString API documentation.Data Type: StringDefault: nullConnection URI Example: readPreferenceTags=dc:ny |
maxStalenessSeconds | Sets the maximum staleness in seconds. To learn more about staleness, see the Class ConnectionString API documentation. Data Type: IntegerDefault: nullConnection URI Example: maxStalenessSeconds=60 |
Configuración del conjunto de réplicas
Opción de conexión | Descripción |
|---|---|
replicaSet | Specifies the name of the replica set to connect to. Data Type: StringDefault: nullConnection URI Example: replicaSet=replicaSet |
Configuración del servidor
Opción de conexión | Descripción |
|---|---|
appName | Sets the logical name of the application. The application name may be used by the client to identify the application to the server, for use in server logs, slow query logs, and profile collection. Data Type: StringDefault: nullConnection URI Example: appName=name |
heartbeatFrequencyMS | The frequency in milliseconds of the driver determining the current state of each server in the cluster. Data Type: IntegerDefault: nullConnection URI Example: heartbeatFrequencyMS=6000 |
localThresholdMS | Sets a ping time threshold for choosing among multiple MongoDB servers to send a request. When this value is set, 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. Data Type: IntegerDefault: nullConnection URI Example: localThresholdMS=6000 |
serverMonitoringMode | Sets the server monitoring mode, which defines the monitoring
protocol to use. The enumerated values are: stream, poll, and auto.Data Type: EnumDefault: autoConnection URI Example: serverMonitoringMode.auto |
Tiempo de espera de selección del servidor MS | Sets how long the driver will wait for server selection to succeed before throwing an exception. Data Type: IntegerDefault: nullConnection URI Example: serverSelectionTimeoutMS=6000 |
Configuración de SRV
Opción de conexión | Descripción |
|---|---|
srvServiceName | Sets the SRV service name. See API documentation to learn more. Data Type: StringDefault: "mongodb"Connection URI Example: srvServiceName=mongodb |
srvMaxHosts | Sets the maximum number of hosts from the SRV record to connect to. Data Type: IntegerDefault: nullConnection URI Example: srvMaxHosts=5 |
Configuración de Escribir Preocupación
Opción de conexión | Descripción |
|---|---|
seguro | Sets whether the driver ensures that all writes are acknowledged by the MongoDB server, or else throws an exception. If false, the driverdoes not ensure that all writes are acknowledged by the MongoDB server. Data Type: booleanDefault: nullConnection URI Example: safe=true |
journal | Sets whether the driver waits for the server to group commit to the journal file on disk. Data Type: booleanDefault: nullConnection URI Example: journal=true |
w | If set, the driver adds { w : wValue } to all write commands. If set,implies that safe=True.Data Type: Integer or StringDefault: nullConnection URI Example: w=60 |
tiempo de espera MS (deprecated) | This option is deprecated. You can configure this timeout by setting the the client-level timeout instead. If set, The driver adds { wtimeout : ms } to all write commands. Ifset, implies safe=true. This option is used in combination with w.Data Type: IntegerDefault: nullConnection URI Example: wtimeoutMS=6000 |
Para obtener más información sobre las opciones de conexión en esta sección, consulte la guía Bases de datos y colecciones.