When you use the Kotlin Sync driver to perform a server operation, you can also limit the amount of time in which the server can finish the operation. To do so, specify a client-side operation timeout (CSOT). The timeout applies to all steps needed to complete the operation, including server selection, connection checkout, and server-side execution. When the timeout expires, the Kotlin Sync driver raises a timeout exception.
Note Experimental FeatureThe CSOT feature is experimental and might change in future driver releases.
To specify a timeout when connecting to a MongoDB deployment, set the timeoutMS
connection option to the timeout length in milliseconds. You can set the timeoutMS
option in the following ways:
Calling the timeout()
method from the MongoClientSettings.Builder
class
Setting the timeoutMS
parameter in your connection string
The following code examples set a client-level timeout of 200
milliseconds. Select the MongoClientSettings or Connection String tab to see the corresponding code.
val settings = MongoClientSettings.builder() .applyConnectionString(ConnectionString("<connection string>")) .timeout(200L, TimeUnit.MILLISECONDS) .build()val client = MongoClient.create(settings)
val uri = "<connection string>/?timeoutMS=200"val client = MongoClient.create(uri)
The following table describes the timeout behavior corresponding to the accepted values for timeoutMS
:
If you specify the timeoutMS
option, the driver automatically applies the specified timeout to each server operation. The following code example specifies a timeout of 200
milliseconds at the client level, and then calls the MongoCollection.insertOne()
method:
val settings = MongoClientSettings.builder() .applyConnectionString(ConnectionString("<connection string>")) .timeout(200L, TimeUnit.MILLISECONDS) .build()MongoClient.create(settings).use { mongoClient -> val database = mongoClient.getDatabase("db") val collection = database.getCollection<Document>("people") collection.insertOne(Document("name", "Francine Loews"))}
When you specify the timeoutMS
option, the driver applies the timeout according to the same inheritance behaviors as the other Kotlin Sync driver options. The following table describes how the timeout value is inherited at each level:
Level
Inheritance Description
Operation
Takes the highest precedence and overrides the timeout options that you set at any other level.
Transaction
Takes precedence over the timeout value that you set at the session, collection, database, or client level.
Session
Applies to all transactions and operations within that session, unless you set a different timeout value at those levels.
Database
Applies to all sessions and operations within that database, unless you set a different timeout value at those levels.
Collection
Applies to all sessions and operations on that collection, unless you set a different timeout value at those levels.
Client
Applies to all databases, collections, sessions, transactions, and operations within that client that do not otherwise specify timeoutMS
.
For more information on overrides and specific options, see the following Overrides section.
The Kotlin Sync driver supports various levels of configuration to control the behavior and performance of database operations.
You can specify a timeoutMS
option at a more specific level to override the client-level configuration. The table in the preceding section describes the levels at which you can specify a timeout setting. This allows you to customize timeouts based on the needs of individual operations.
The following example demonstrates how a collection-level timeout configuration can override a client-level timeout configuration:
val settings = MongoClientSettings.builder() .applyConnectionString(ConnectionString("<connection string>")) .timeout(200L, TimeUnit.MILLISECONDS) .build()MongoClient.create(settings).use { mongoClient -> val database = mongoClient.getDatabase("db") val collection = database .getCollection<Document>("people") .withTimeout(300L, TimeUnit.MILLISECONDS)}
When you create a new ClientSession instance to implement a transaction, use the defaultTimeout()
method when building a ClientSessionOptions
instance. You can use this option to specify the timeout for the following methods:
The following code demonstrates how to set the defaultTimeout
when instantiating a ClientSession
:
val opts = ClientSessionOptions.builder() .defaultTimeout(200L, TimeUnit.MILLISECONDS) .build()val session = mongoClient.startSession(opts)
If you do not specify the defaultTimeout
, the driver uses the timeout value set on the parent MongoClient
.
You can also set a transaction-level timeout by calling the timeout()
method when building a TransactionOptions
instance. Setting this option applies a timeout to all operations performed in the scope of the transaction:
val transactionOptions = TransactionOptions.builder() .timeout(200L, TimeUnit.MILLISECONDS) .build()
To learn more about transactions, see the Transactions guide.
When you use Client-Side Field Level Encryption (CSFLE), the driver uses the timeoutMS
option to limit the time allowed for encryption and decryption operations. You can set a timeout option for your ClientEncryption
instance by calling the timeout()
method when building a ClientEncryptionSettings
instance.
If you specify the timeout when you construct a ClientEncryption
instance, the timeout controls the lifetime of all operations performed on that instance. If you do not provide a timeout when instantiating ClientEncryption
, the instance inherits the timeout setting from the MongoClient
used in the ClientEncryption
constructor.
If you set timeoutMS
both on the client and directly in ClientEncryption
, the value provided to ClientEncryption
takes precedence.
Cursors offer configurable timeout settings when using the CSOT feature. You can adjust cursor handling by configuring either the cursor lifetime or cursor iteration mode. To configure the timeout mode, use the timeoutMode()
method when performing any operation that returns an Iterable
.
For operations that create cursors, the timeout setting can either cap the lifetime of the cursor or be applied separately to the original operation and all subsequent calls.
Note Inherited TimeoutSetting a cursor timeout mode requires that you set a timeout either in the MongoClientSettings
, on MongoDatabase
, or on MongoCollection
.
To learn more about cursors, see the Access Data From a Cursor guide.
The cursor lifetime mode uses the timeout setting to limit the entire lifetime of a cursor. In this mode, your application must initialize the cursor, complete all calls to the cursor methods, and return all documents within the specified time limit. Otherwise, the cursor's lifetime expires and the driver raises a timeout error.
When you close a cursor by calling the close()
method, the timeout resets for the killCursors
command to ensure server-side resources are cleaned up.
The following example shows how to set a cursor timeout to ensure that the cursor is initialized and all documents are retrieved within the inherited timeout:
val cursorWithLifetimeTimeout = collection .find(Filters.gte("age", 40)) .timeoutMode(TimeoutMode.CURSOR_LIFETIME)
The cursor iteration mode sets the timeout to limit each call to the next()
, hasNext()
, and tryNext()
methods. The timeout refreshes after each call completes. This is the default mode for all tailable cursors, such as the tailable cursors returned by the find()
method on capped collections or change streams.
The following code example iterates over documents in the db.people
collection by using a cursor with the ITERATION
timeout mode, and then retrieves and prints the name
field value for each document:
collection .find(Filters.gte("age", 40)) .timeoutMode(TimeoutMode.ITERATION) .cursor().use { cursorWithIterationTimeout -> while (cursorWithIterationTimeout.hasNext()) { println(cursorWithIterationTimeout.next().toJson()) } }
To learn more about using timeouts with the Kotlin Sync driver, see the following API documentation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4