Overview
すべてのMongoDBドライバーは、読み取りまたは書き込みのサーバーを選択するときに定義されたアルゴリズムに従います。MongoClientSettings
オブジェクトの ClusterSettings
プロパティを使用すると、このアルゴリズムをカスタマイズして、サーバーに最適です。
重要
サーバー選択アルゴリズムをカスタマイズすると、読み取りや書込みパフォーマンスの低下など、意図しない結果が生じる可能性があります。
サーバー選択アルゴリズム
Kotlin Syncドライバーが 読み取り操作を実行するとき、次の手順を順番に実行してMongoDBデプロイを選択します。
要求された操作に適したすべてのサーバーを既知のサーバーのリストから選択します。ただし、ドライバーが使用できないサーバーや問題が発生したと判断されたサーバーは除外されます。
読み取りの場合、アクティブな読み込み設定 (read preference)に一致するすべてのサーバーを選択します
書き込みの場合、すべての書き込み可能なサーバーを選択します
ユーザー定義のサーバー セレクター関数(ユーザーが指定したサーバー セレクター関数を指定した場合)を呼び出し、前のステップのリストが渡されます
関数から返されるサーバーのリストに
localThreshold
接続設定を適用します前述の条件に一致するサーバーのリストから最大 2 つのランダムなサーバーを選択し、未処理の同時操作が少ないサーバーを選択します
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 で、次のサーバー選択設定を指定できます。
設定 | 説明 | |||
---|---|---|---|---|
| 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 | |||
| 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:
| |||
| 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 ドキュメント
このガイドで使用されているクラスとメソッドの詳細については、次のAPIドキュメントを参照してください。