|
| 1 | +.. _java-configure-replica-sets: |
| 2 | + |
| 3 | +==================================== |
| 4 | +Configure Operations on Replica Sets |
| 5 | +==================================== |
| 6 | + |
| 7 | +.. facet:: |
| 8 | + :name: genre |
| 9 | + :values: reference |
| 10 | + |
| 11 | +.. meta:: |
| 12 | + :keywords: customize, preferences, replica set, consistency |
| 13 | + |
| 14 | +.. contents:: On this page |
| 15 | + :local: |
| 16 | + :backlinks: none |
| 17 | + :depth: 2 |
| 18 | + :class: singlecol |
| 19 | + |
| 20 | +Overview |
| 21 | +-------- |
| 22 | + |
| 23 | +In this guide, you can learn how to configure **write concern**, **read concern**, |
| 24 | +and **read preference** options to modify the way that the {+driver-short+} runs |
| 25 | +read and write operations on replica sets. |
| 26 | + |
| 27 | +Read and Write Settings Precedence |
| 28 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 29 | + |
| 30 | +You can set write concern, read concern, and read preference options at the following |
| 31 | +levels: |
| 32 | + |
| 33 | +- Client, which sets the *default for all operation executions* unless overridden |
| 34 | +- Transaction |
| 35 | +- Database |
| 36 | +- Collection |
| 37 | + |
| 38 | +This list also indicates the increasing order of precedence of the option settings. For |
| 39 | +example, if you set a read concern for a transaction, it will override the read |
| 40 | +concern settings inherited from the client. |
| 41 | + |
| 42 | +Write concern, read concern, and read preference options allow you to customize the |
| 43 | +causal consistency and availability of the data in your replica sets. To see a full |
| 44 | +list of these options, see the following guides in the {+mdb-server+} manual: |
| 45 | + |
| 46 | +- :manual:`Read Preference </core/read-preference/>` |
| 47 | +- :manual:`Read Concern </reference/read-concern/>` |
| 48 | +- :manual:`Write Concern </reference/write-concern/>` |
| 49 | + |
| 50 | +.. _java-read-write-config: |
| 51 | + |
| 52 | +Configure Read and Write Operations |
| 53 | +----------------------------------- |
| 54 | + |
| 55 | +You can control how the driver routes read operations among replica set members |
| 56 | +by setting a read preference. You can also control how the driver waits for |
| 57 | +acknowledgment of read and write operations on a replica set by setting read and |
| 58 | +write concerns. |
| 59 | + |
| 60 | +The following sections show how to configure these read and write settings |
| 61 | +at various levels. |
| 62 | + |
| 63 | +.. _java-read-write-client: |
| 64 | + |
| 65 | +Client Configuration |
| 66 | +~~~~~~~~~~~~~~~~~~~~ |
| 67 | + |
| 68 | +This example shows how to set the read preference, read concern, and |
| 69 | +write concern of a ``MongoClient`` instance by passing a ``MongoClientSettings`` |
| 70 | +instance to the constructor. The code configures the following settings: |
| 71 | + |
| 72 | +- ``secondary`` read preference: Read operations retrieve data from |
| 73 | + secondary replica set members. |
| 74 | +- ``LOCAL`` read concern: Read operations return the instance's most recent data |
| 75 | + without guaranteeing that the data has been written to a majority of the replica |
| 76 | + set members. |
| 77 | +- ``W2`` write concern: The primary replica set member and one secondary member |
| 78 | + must acknowledge the write operation. |
| 79 | + |
| 80 | +.. literalinclude:: /includes/fundamentals/code-snippets/ReplicaSets.java |
| 81 | + :language: java |
| 82 | + :dedent: |
| 83 | + :start-after: start-client-settings |
| 84 | + :end-before: end-client-settings |
| 85 | + |
| 86 | +Alternatively, you can specify the read and write settings in the connection |
| 87 | +URI, which is passed as a parameter to the ``MongoClients`` constructor: |
| 88 | + |
| 89 | +.. literalinclude:: /includes/fundamentals/code-snippets/ReplicaSets.java |
| 90 | + :language: java |
| 91 | + :dedent: |
| 92 | + :start-after: start-client-settings-uri |
| 93 | + :end-before: end-client-settings-uri |
| 94 | + |
| 95 | +.. _java-read-write-transaction: |
| 96 | + |
| 97 | +Transaction Configuration |
| 98 | +~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 99 | + |
| 100 | +This example shows how to set the read preference, read concern, and |
| 101 | +write concern of a transaction by passing a ``TransactionOptions`` |
| 102 | +instance to the ``startTransaction()`` method. Transactions run within |
| 103 | +**sessions**, which are groupings of related read or write operations that you |
| 104 | +intend to run sequentially. Before applying the transaction options, create a |
| 105 | +``ClientSession`` instance to start a session. |
| 106 | + |
| 107 | +.. tip:: |
| 108 | + |
| 109 | + To learn more about sessions, see :manual:`Server Sessions </reference/server-sessions/>` |
| 110 | + in the {+mdb-server+} manual. |
| 111 | + |
| 112 | +The example configures the following settings: |
| 113 | + |
| 114 | +- ``primary`` read preference: Read operations retrieve data from |
| 115 | + the primary replica set member. |
| 116 | +- ``MAJORITY`` read concern: Read operations return the instance's most recent data |
| 117 | + that has been written to a majority of replica set members. |
| 118 | +- ``W1`` write concern: The primary replica set member must acknowledge the |
| 119 | + write operation. |
| 120 | + |
| 121 | +.. literalinclude:: /includes/fundamentals/code-snippets/ReplicaSets.java |
| 122 | + :language: java |
| 123 | + :dedent: |
| 124 | + :start-after: start-transaction-settings |
| 125 | + :end-before: end-transaction-settings |
| 126 | + |
| 127 | +.. _java-read-write-database: |
| 128 | + |
| 129 | +Database Configuration |
| 130 | +~~~~~~~~~~~~~~~~~~~~~~ |
| 131 | + |
| 132 | +This example shows how to set the read preference, read concern, and |
| 133 | +write concern of a database called ``test_database`` by chaining setter |
| 134 | +methods to the ``getDatabase()`` method. The code configures the following |
| 135 | +settings: |
| 136 | + |
| 137 | +- ``primaryPreferred`` read preference: Read operations retrieve data from |
| 138 | + the primary replica set member, or secondary members if the primary is unavailable. |
| 139 | +- ``AVAILABLE`` read concern: Read operations return the instance's most recent data |
| 140 | + without guaranteeing that the data has been written to a majority of the replica |
| 141 | + set members. |
| 142 | +- ``MAJORITY`` write concern: The majority of all replica set members |
| 143 | + must acknowledge the write operation. |
| 144 | + |
| 145 | +.. literalinclude:: /includes/fundamentals/code-snippets/ReplicaSets.java |
| 146 | + :language: java |
| 147 | + :dedent: |
| 148 | + :start-after: start-database-settings |
| 149 | + :end-before: end-database-settings |
| 150 | + |
| 151 | +.. _java-read-write-collection: |
| 152 | + |
| 153 | +Collection Configuration |
| 154 | +~~~~~~~~~~~~~~~~~~~~~~~~ |
| 155 | + |
| 156 | +This example shows how to set the read preference, read concern, and |
| 157 | +write concern of a collection called ``test_collection`` by chaining setter |
| 158 | +methods to the ``getCollection()`` method. The code configures the following |
| 159 | +settings: |
| 160 | + |
| 161 | +- ``secondaryPreferred`` read preference: Read operations retrieve data from |
| 162 | + secondary replica set members, or the primary members if no secondary members are |
| 163 | + available. |
| 164 | +- ``AVAILABLE`` read concern: Read operations return the instance's most recent data |
| 165 | + without guaranteeing that the data has been written to a majority of the replica |
| 166 | + set members. |
| 167 | +- ``UNACKNOWLEDGED`` write concern: Replica set members do not need to acknowledge |
| 168 | + the write operation. |
| 169 | + |
| 170 | +.. literalinclude:: /includes/fundamentals/code-snippets/ReplicaSets.java |
| 171 | + :language: java |
| 172 | + :dedent: |
| 173 | + :start-after: start-collection-settings |
| 174 | + :end-before: end-collection-settings |
| 175 | + |
| 176 | +.. _java-read-write-advanced: |
| 177 | + |
| 178 | +Advanced Read Configurations |
| 179 | +---------------------------- |
| 180 | + |
| 181 | +The following sections describe ways to further customize how the {+driver-short+} |
| 182 | +routes read operations. |
| 183 | + |
| 184 | +.. _java-sharded-clusters: |
| 185 | + |
| 186 | +Sharded Clusters |
| 187 | +~~~~~~~~~~~~~~~~ |
| 188 | + |
| 189 | +You can specify a read preference when connecting to a sharded cluster. |
| 190 | +MongoDB uses sharding to divide datasets by key ranges and distribute data across multiple |
| 191 | +database instances. A sharded cluster, or the set of nodes in a sharded deployment, |
| 192 | +includes the following components: |
| 193 | + |
| 194 | +- **Shard**: A replica set that contains a subset of the sharded data. |
| 195 | +- **Mongos**: A query router that provides an interface between your |
| 196 | + application and the sharded cluster. |
| 197 | +- **Config servers**: Servers that store the cluster's configuration settings |
| 198 | + and metadata. |
| 199 | + |
| 200 | +.. tip:: |
| 201 | + |
| 202 | + To learn more about sharded clusters, see :manual:`Sharding </sharding/>` |
| 203 | + in the {+mdb-server+} manual. |
| 204 | + |
| 205 | +When reading from the replica set shards, mongos applies your specified read |
| 206 | +preference. The read preference is re-evaluated for each operation. |
| 207 | + |
| 208 | +The following example shows how to connect to a sharded cluster and specify a |
| 209 | +``secondary`` read preference in your connection string: |
| 210 | + |
| 211 | +.. literalinclude:: /includes/fundamentals/code-snippets/ReplicaSets.java |
| 212 | + :language: java |
| 213 | + :dedent: |
| 214 | + :start-after: start-sharded-cluster-uri |
| 215 | + :end-before: end-sharded-cluster-uri |
| 216 | + |
| 217 | +.. _java-tag-sets: |
| 218 | + |
| 219 | +Tag Sets |
| 220 | +~~~~~~~~ |
| 221 | + |
| 222 | +In {+mdb-server+}, you can apply key-value :manual:`tags |
| 223 | +</core/read-preference-tags/>` to replica set members |
| 224 | +according to any criteria you choose. You can then use those |
| 225 | +tags to target one or more members for a read operation. |
| 226 | + |
| 227 | +By default, the {+driver-short+} ignores tags when choosing a member |
| 228 | +to read from. To instruct the {+driver-short+} to prefer certain tags, |
| 229 | +pass the tags as a list to your read preference setter method. |
| 230 | + |
| 231 | +Suppose you are connected to a replica set that contains members hosted |
| 232 | +at multiple data centers across the United States. You want the driver to |
| 233 | +prefer reads from secondary replica set members in the following order: |
| 234 | + |
| 235 | +1. Members from the New York data center, tagged with ``("dc", "ny")`` |
| 236 | +#. Members from the San Francisco data center, tagged with ``("dc", "sf")`` |
| 237 | +#. Any secondary members |
| 238 | + |
| 239 | +This code example passes a list of tags representing the preceding replica |
| 240 | +set members to the ``ReadPreference.secondary()`` setter method. Then, the code |
| 241 | +passes the read preference information to the ``withReadPreference()`` method |
| 242 | +to set the read order on the database: |
| 243 | + |
| 244 | +.. literalinclude:: /includes/fundamentals/code-snippets/ReplicaSets.java |
| 245 | + :language: java |
| 246 | + :dedent: |
| 247 | + :start-after: start-tag-set |
| 248 | + :end-before: end-tag-set |
| 249 | + |
| 250 | +Load Balancing |
| 251 | +~~~~~~~~~~~~~~ |
| 252 | + |
| 253 | +When connecting to a sharded cluster or a replica set, the {+driver-short+} uses |
| 254 | +**load balancing** to handle read and write requests. Load balancing allows the driver to |
| 255 | +distribute these requests across multiple servers, which avoids overwhelming |
| 256 | +any one server and ensures optimal performance. |
| 257 | + |
| 258 | +When connecting to a sharded cluster, the {+driver-short+} determines the closest mongos |
| 259 | +instance by calculating which one has the lowest network round-trip time. Then, the driver |
| 260 | +determines the latency window by adding this mongos's average round-trip time to the |
| 261 | +:ref:`localThresholdMS value <java-local-threshold>`. The driver load balances requests |
| 262 | +across up to two random mongos instances that fall within the latency window. For each request, |
| 263 | +the driver chooses the server with the lower operation load by determining its ``operationCount`` |
| 264 | +value. |
| 265 | + |
| 266 | +When connecting to a replica set, the {+driver-short+} first selects replica set members |
| 267 | +according to your read preference. Then, the driver follows the same process as |
| 268 | +described in the preceding paragraph. After calculating the latency window, the driver |
| 269 | +selects up to two random replica set members that fall within the window and chooses |
| 270 | +the member with the lower ``operationCount`` value to receive the request. |
| 271 | + |
| 272 | +.. tip:: |
| 273 | + |
| 274 | + To learn more about load balancing, see :manual:`Sharded Cluster Balancer |
| 275 | + </core/sharding-balancer-administration/>` in the {+mdb-server+} manual. |
| 276 | + |
| 277 | + To learn how to customize the driver's server selection behavior, see |
| 278 | + :ref:`mcs-cluster-settings` in the Specify MongoClient Settings guide. |
| 279 | + |
| 280 | +.. _java-local-threshold: |
| 281 | + |
| 282 | +Local Threshold |
| 283 | +``````````````` |
| 284 | + |
| 285 | +The {+driver-short+} uses the local threshold value to calculate the |
| 286 | +latency window for server selection. This value determines the servers |
| 287 | +that are eligible to receive read and write requests. |
| 288 | + |
| 289 | +By default, the driver uses only mongos instances or replica set members whose |
| 290 | +ping times are within 15 milliseconds of the nearest server. To |
| 291 | +distribute reads among servers with higher latencies, set the ``localThreshold`` |
| 292 | +option in a ``MongoClientSettings`` instance or the ``localThresholdMS`` option |
| 293 | +in your connection URI. |
| 294 | + |
| 295 | +.. note:: |
| 296 | + |
| 297 | + When selecting replica set members from a single mongos instance, the |
| 298 | + {+driver-short+} ignores the ``localThresholdMS`` option. In this case, use the |
| 299 | + :manual:`localThreshold </reference/program/mongos/#std-option-mongos.--localThreshold>` |
| 300 | + command-line option. |
| 301 | + |
| 302 | +The following example connects to a replica set and specifies a local threshold |
| 303 | +of 35 milliseconds. Select the :guilabel:`MongoClientSettings` or :guilabel:`Connection URI` |
| 304 | +tab to see corresponding code for each approach: |
| 305 | + |
| 306 | +.. tabs:: |
| 307 | + |
| 308 | + .. tab:: MongoClientSettings |
| 309 | + :tabid: settings |
| 310 | + |
| 311 | + .. literalinclude:: /includes/fundamentals/code-snippets/ReplicaSets.java |
| 312 | + :language: rust |
| 313 | + :dedent: |
| 314 | + :start-after: start-local-threshold-settings |
| 315 | + :end-before: end-local-threshold-settings |
| 316 | + |
| 317 | + |
| 318 | + .. tab:: Connection URI |
| 319 | + :tabid: uri |
| 320 | + |
| 321 | + .. literalinclude:: /includes/fundamentals/code-snippets/ReplicaSets.java |
| 322 | + :language: rust |
| 323 | + :dedent: |
| 324 | + :start-after: start-local-threshold-uri |
| 325 | + :end-before: end-local-threshold-uri |
| 326 | + |
| 327 | +In the preceding example, the {+driver-short+} distributes reads among matching members |
| 328 | +within 35 milliseconds of the closest member's ping time. |
| 329 | + |
| 330 | +API Documentation |
| 331 | +----------------- |
| 332 | + |
| 333 | +To learn more about any of the methods or types discussed in this |
| 334 | +guide, see the following API documentation: |
| 335 | + |
| 336 | +- `MongoClient <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoClient.html>`__ |
| 337 | +- `MongoClientSettings <{+api+}/apidocs/mongodb-driver-core/com/mongodb/MongoClientSettings.html>`__ |
| 338 | +- `TransactionOptions <{+api+}/apidocs/mongodb-driver-core/com/mongodb/TransactionOptions.html>`_ |
| 339 | +- `startTransaction() <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/ClientSession.html#startTransaction()>`_ |
| 340 | +- `MongoDatabase <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoDatabase.html>`__ |
| 341 | +- `MongoCollection <{+api+}/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html>`__ |
| 342 | +- `TagSet <{+api+}/apidocs/mongodb-driver-core/com/mongodb/TagSet.html>`_ |
0 commit comments