Docs 菜单
Docs 主页
/ / /
java sync
/ /

指定 MongoClient 设置

在此页面上

  • Overview
  • MongoClient 设置
  • 群集设置
  • 连接池设置
  • 服务器设置
  • 套接字设置
  • TLS/SSL 设置

在本指南中,您可以学习控制 MongoClient 行为的几种不同设置。

以下各部分介绍了常用设置:

  • MongoClient 设置

  • 群集设置

  • 套接字设置

  • 连接池设置

  • 服务器设置

  • TLS/SSL 设置

可以通过创建 MongoClientSettings 对象并将其传递给 MongoClients.create() 方法来控制 MongoClient 的行为。

要创建 MongoClientSettings 对象,请使用 MongoClientSettings.builder() 方法和链接方法指定设置。将它们链接起来后,使用 build() 方法创建 MongoClientSettings 对象。

下表描述了可以链式调用以修改连接行为的所有方法:

方法
说明
addCommandListener()
命令事件添加侦听器。
applicationName()
使用 MongoClient 设置应用程序的逻辑名称。
applyConnectionString()
将给定 ConnectionString 中的设置应用于构建器。如果省略该方法,该驱动程序将尝试连接到 localhost
applyToClusterSettings()
应用 ClusterSettings.Builder 块,然后设置集群设置
applyToConnectionPoolSettings()
应用 ConnectionPoolSettings.Builder 块,然后设置连接池设置。
applyToServerSettings()
应用 ServerSettings.Builder 块,然后设置服务器设置。
applyToSocketSettings()
应用 SocketSettings.Builder 块,然后设置套接字设置。
applyToSslSettings()
应用 SslSettings.Builder 块,然后设置 TLS/SSL 设置
autoEncryptionSettings()

If you omit keyVaultClient or set bypassAutomaticEncryption to false in your AutoEncryptionSettings, the driver creates a separate, internal MongoClient.

The internal MongoClient configuration differs from the parent MongoClient by setting the minPoolSize to 0 and omitting the AutoEncryptionSettings.
codecRegistry()
commandListenerList()
compressorList()
设置用于压缩发送到服务器的消息的压缩器
credential()
设置档案
readConcern()
readPreference()
Sets the read preference.

Default: primary
retryReads()
Whether the driver performs retry reads if a network error occurs.

Default: true
retryWrites()
Whether the driver performs retry writes if a network error occurs.

Default: true
serverApi()
设置向服务器发送命令时使用的服务器 API
streamFactoryFactory()
设置用于创建 StreamFactory 的工厂。
uuidRepresentation()
设置在编码 UUID 实例和解码子类型为 3 的 BSON 二进制值时使用的 UUID 表示。
writeConcern()
Sets the write concern.

Default: WriteConcern#ACKNOWLEDGED. For more information about the default value, see Implicit Default Write Concern.

此示例演示如何指定 ConnectionString

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyConnectionString(new ConnectionString("<your connection string>"))
.build());

注意

连锁订单

设置中的某些选项映射到连接字符串选项。如果在设置和连接字符串中指定相同的选项,则链接这些选项的顺序将决定驱动程序使用的选项。驱动程序使用其读取的最后一项设置。

例如,此代码段包含驱动程序连接到可用套接字的以下时间的设置:

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb+srv://<db_username>:<db_password>@<hostname>:<port>/<auth db>?connectTimeoutMS=2000"))
.applyToSocketSettings(builder ->
builder.connectTimeout(5, SECONDS))
.build());

由于驱动程序最后才读取套接字设置选项,因此驱动程序希望在超时前的 5 SECONDS 内连接到可用的套接字。

提示

记录您的设置

要记录 MongoClient 实例设置,请将名为 logger 的 org.mongodb.driver.client 设置为 INFO 级别。

要了解有关使用 MongoDB Java 驱动程序进行日志记录的更多信息,请参阅日志记录指南。

链接 applyToClusterSettings() 方法修改驱动程序在与 MongoDB 集群交互时的行为。

下表描述了可以链接到设置以修改驱动程序行为的所有方法:

方法
说明
addClusterListener()
为集群相关事件添加侦听器。
applyConnectionString()
使用 ConnectionString 对象中的设置。
applySettings()
使用在 ClusterSettings 对象中指定的集群设置。
hosts()
设置 Mongo 部署的所有指定位置。
localThreshold()
Sets the amount of time that a server’s round trip can take and still be eligible for server selection.

Default: 15 milliseconds
mode()
设置如何连接到 MongoDB 部署。
requiredClusterType()
设置集群所需的集群类型。
requiredReplicaSetName()
设置集群所需的副本集名称。
serverSelectionTimeout()
Sets the maximum time to select a primary node before throwing a timeout exception.

Default: 30 seconds
serverSelector()
添加服务器选择器,在选择服务器前应用。
srvHost()

设置用于查找 SRV DNS 记录的主机名,以查找 MongoDB 主机。

注意

设置 srvHost 时,驱动程序不会处理与主机关联的任何 TXT 记录。

如果要启用 TXT 记录处理,必须使用 applyConnectionString() 方法在连接字符串中指定 SRV 主机。

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyConnectionString(new ConnectionString("mongodb+srv://host1.acme.com")))
srvMaxHosts()
Sets the maximum number of hosts the driver can connect to when using the DNS seedlist (SRV) connection protocol, identified by the mongodb+srv connection string prefix.

Throws an exception if you are not using the SRV connection protocol.

此示例指定驱动程序直接连接到服务器,无论它隶属哪种类型的 MongoDB 集群:

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder ->
builder.mode(ClusterConnectionMode.SINGLE)
.build());

提示

此操作类似于在连接 URI 中指定的 directConnection 参数。有关更多信息,请参阅“连接选项”。

链接 applyToConnectionPoolSettings() 方法来修改驱动程序管理其连接池的方式。

下表描述了可以链接到设置以修改驱动程序行为的所有方法:

方法
说明
addConnectionPoolListener()
添加监听器,用于监听与连接池相关的事件。
applyConnectionString()
使用 ConnectionString 对象中的设置。
applySettings()
使用在 ConnectionPoolSettings 对象中指定的连接池设置。
maintenanceFrequency()
设置运行维护作业的频率。
maintenanceInitialDelay()
设置运行第一个维护作业之前的等待时间。
maxConnectionIdleTime()
设置连接在关闭之前可以空闲的最长时间。
maxConnectionLifeTime()
设置池式连接在关闭之前可以存活的最长时间。
maxSize()
Sets the maximum number of connections associated with a connection pool.

Default: 100
maxWaitTime()
Sets the maximum time to wait for an available connection.

Default: 2 minutes
minSize()
Sets the minimum number of connections associated with a connection pool.

Default: 0

注意

maxSizeminSize设置适用于驱动程序连接到的集群中的每台服务器。

例如,假设您将驱动程序连接到一个有三台 mongos 服务器的集群。这意味着每台mongos服务器最多可以有maxSize个连接,至少有minSize个连接。

此示例在 Connection 类型池中指定以下驱动程序行为:

  • 线程最多等待可用连接 10 SECONDS

  • 最多有 200 个与池关联的连接

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(new ConnectionString("<your connection string>"))
.applyToConnectionPoolSettings(builder ->
builder.maxWaitTime(10, SECONDS)
.maxSize(200)
.build());

链接 applyToServerSettings() 方法来修改驱动程序在监控每个 MongoDB 部署时的行为。

下表描述了可以链接到设置以修改驱动程序行为的所有方法:

方法
说明
addServerListener()
为服务器相关事件添加侦听器。
addServerMonitorListener()
为服务器监视器相关事件添加侦听器。
applyConnectionString()
使用 ConnectionString 对象中的设置。
applySettings()
使用 ServerSettings 对象中指定的服务器设置。
heartbeatFrequency()
Sets the interval for a cluster monitor to attempt reaching a server.

Default: 10 seconds
minHeartbeatFrequency()
Sets the minimum interval for server monitoring checks.

Default: 500 milliseconds

此示例在 MongoDB 部署中指定了以下驱动程序行为:

  • 服务器监控检查的最小间隔至少为 700 MILLISECONDS

  • 集群监视器尝试访问服务器的时间间隔为 15 SECONDS

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(new ConnectionString("<your connection string>"))
.applyToServerSettings(builder ->
builder.minHeartbeatFrequency(700, MILLISECONDS)
.heartbeatFrequency(15, SECONDS))
.build());

链接 applyToSocketSettings() 方法,修改驱动程序在与 MongoDB 部署连接并通信时的行为。

下表描述了可以链接到设置以修改驱动程序行为的方法:

方法
说明
applyConnectionString()
使用 ConnectionString 对象中的设置。
applySettings()
使用在 SocketSettings 对象中指定的套接字设置。
connectTimeout()
Sets the maximum time to connect to an available socket before throwing a timeout exception.

Default: 10 seconds
readTimeout()
Sets the maximum time to read from an available socket before throwing a timeout exception.

Default: 0, which indicates no timeout
receiveBufferSize()
Sets the socket's buffer size when receiving.

Default: The operating system default
sendBufferSize()
Sets the socket's buffer size when sending.

Default: The operating system default

本示例在 MongoDB 套接字中指定了以下驱动程序行为:

  • 连接到可用套接字 10 SECONDS

  • 从可用套接字读取,在 15 SECONDS

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(new ConnectionString("<your connection string>"))
.applyToSocketSettings(builder ->
builder.connectTimeout(10, SECONDS)
.readTimeout(15, SECONDS))
.build());

链接 applyToSslSettings() 方法修改使用 TLS/SSL 保护应用程序与 MongoDB 之间的连接时驱动程序的行为。

下表描述了可以链接到设置以修改驱动程序行为的所有方法:

方法
说明
applyConnectionString()
使用 ConnectionString 对象中的设置。
applySettings()
使用在 SslSettings 对象中指定的 TLS/SSL 设置。
context()
设置启用 TLS/SSL 时使用的 SSLContext
enabled()
是否启用 TLS/SSL。(必须为 Atlas 集群启用此选项)。
invalidHostNameAllowed()
是否允许服务器主机名与 TLS 证书指定的主机名不匹配。

此示例规定了驱动程序要在连接 MongoDB 时启用 TLS/SSL:

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(new ConnectionString("<your connection string>"))
.applyToSslSettings(builder ->
builder.enabled(true))
.build());

后退

连接选项