Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Kotlin Sync 驱动程序
/ /

自定义MongoDB Server选择

所有MongoDB驱动程序在选择要读取或写入的服务器时都遵循定义的算法。通过使用 MongoClientSettings对象的 ClusterSettings属性,您可以自定义此算法以选择最适合您的应用程序的服务器。

重要

自定义服务器选择算法可能会产生意想不到的后果,例如读取或写入性能下降。

当Kotlin Sync驾驶员执行读取操作时,它会按顺序执行以下步骤,以选择MongoDB 部署:

  1. 从适合请求操作的已知服务器列表中选择所有服务器,驾驶员认为不可用或有问题的服务器除外

    1. 对于读取,选择与活动读取偏好(read preference)匹配的所有服务器

    2. 对于写入,请选择所有可写入的服务器

  2. 调用用户定义的服务器选择器函数(如果用户提供了该函数),并传入上一步中的列表

  3. localThreshold 连接设置应用于从该函数返回的服务器列表

  4. 从符合上述条件的服务器列表中随机选择最多两台服务器,然后选择具有较少未完成并发操作的服务器

当Kotlin Sync驾驶员执行写入操作时,它首先从已知服务器列表中选择所有可写入的服务器,而不仅仅是那些与活动读取偏好(read preference)匹配的服务器。其余步骤与前面的列表相同。

要学习;了解有关MongoDB服务器选择算法的更多信息,请参阅MongoDB Server手册中的 服务器选择算法

您可以通过创建实现 ServerSelector 接口的类实现自己的自定义服务器选择逻辑。以下示例显示了一个简单的自定义服务器选择类,该类选择 type 值为 ServerType.REPLICA_SET_SECONDARY 的服务器:

class CustomServerSelector : ServerSelector {
override fun select(cluster: ClusterDescription): List<ServerDescription> {
return cluster.serverDescriptions.filter { it.type == ServerType.REPLICA_SET_SECONDARY }
}
}

使用 applyToClusterSettings() 方法将此类的实例传递给 MongoClientSettings。以下示例展示了如何使用上一示例中的自定义服务器选择器类的实例创建 MongoClient

val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString("<connection URI>"))
.applyToClusterSettings { builder ->
builder.serverSelector(CustomServerSelector())
}
.build()
val mongoClient = MongoClient.create(settings)

您可以在 MongoClient对象或连接 URI 中指定以下服务器选择设置:

设置
说明

localThreshold

The latency window for server eligibility. If a server's round trip takes longer
than the fastest server's round-trip time plus this value, the server isn't
eligible for selection. You can specify this setting to a ClusterSettings object in addition to the connection URI.

Data Type: Integer
Default: 15 milliseconds
Connection URI Example: localThresholdMS=0

readPreference

The client's default read-preference settings. For more information on read preference options, see Read Preference in the MongoDB Server manual. You can specify this setting to a MongoClientSettings object in addition to the connection URI.

Data Type: ReadPreference
Default: ReadPreference.primary()
Connection URI Example:
readPreference=primaryPreferred
&maxStalenessSeconds=90
&readPreferenceTags=dc:ny,rack:1

serverSelectionTimeout

The length of time the driver tries to select a server before timing out. You can specify this setting to a ClusterSettings object in addition to the connection URI.

Data Type: Long
Default: 30 seconds
Connection URI Example: serverSelectionTimeoutMS=15000

要学习;了解有关本指南中使用的类和方法的更多信息,请参阅以下API文档:

后退

网络压缩

在此页面上