Docs 菜单
Docs 主页
/ / /
Kotlin Sync 驱动程序
/

事务

在此页面上

  • Overview
  • 样本数据
  • 方法
  • 例子
  • 更多信息
  • API 文档

在本指南中,您可以学习;了解如何使用Kotlin Sync驾驶员来执行事务。事务允许您运行一系列操作,这些操作在提交ACID 事务之前不会更改任何数据。如果ACID 事务中的任何操作返回错误,驾驶员就会取消ACID 事务,并在所有数据更改变得可见之前将其丢弃。

在 MongoDB 中,事务在逻辑会话中运行。会话是您打算按顺序运行的一组相关读取或写入操作。会话为一组操作启用因果一致性,并允许您在符合 ACID 的事务中运行操作,该事务满足原子性、一致性、隔离性和持久性的预期。 MongoDB 保证事务操作中涉及的数据保持一致,即使操作遇到意外错误。

使用Kotlin Sync驾驶员时,您可以从 MongoClient实例创建一个新会话,并将其类型定义为ClientSession 。我们建议您将MongoClient重复用于多个会话和事务,而不是每次都创建一个新客户端。

警告

仅应将 ClientSession 与创建它的 MongoClient(或关联的 MongoDatabaseMongoCollection)一起使用。将 ClientSession 与其他 MongoClient 一起使用会导致操作错误。

本指南中的示例使用 Atlas 样本数据集中sample_restaurants.restaurants集合。要了解如何创建免费的 MongoDB Atlas 集群并加载样本数据集,请参阅Atlas 入门指南。

此集合中的文档由以下 Kotlin 数据类建模:

data class Restaurant(val name: String, val cuisine: String)

MongoClient实例上使用startSession()方法创建ClientSession 。然后,您可以使用ClientSession提供的方法修改会话状态。下表描述了可用于管理事务的方法:

方法
说明
startTransaction()
Starts a new transaction, configured with the given options, on this session. Returns an error if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the Server manual.

Parameter: TransactionOptions
abortTransaction()
Ends the active transaction for this session. Returns an error if there is no active transaction for the session or the transaction has been committed or ended. To learn more about this method, see the abortTransaction() page in the Server manual.

commitTransaction()
Commits the active transaction for this session. Returns an error if there is no active transaction for the session or if the transaction was ended. To learn more about this method, see the commitTransaction() page in the Server manual.
withTransaction()
Starts a transaction on this session and runs the given function within a transaction.

Parameters: transaction body function, TransactionOptions

以下示例演示了如何通过以下步骤创建会话、创建ACID 事务以及在一个ACID 事务中将文档插入到集合中:

  1. 使用 startSession() 方法从客户端创建会话。

  2. 定义insertRestaurantsInTransaction()方法以将多个文档插入到restaurants集合中。

  3. 使用withTransaction()方法启动ACID 事务。 withTransaction()方法运行插入操作并提交ACID 事务。如果任何操作导致错误, withTransaction()将取消该ACID 事务。

  4. 使用MongoClient.close()方法关闭与服务器的连接。

// Creates a new MongoClient to manage your connection
val client = MongoClient.create("<connection string>")
// Gets the database and collection
val database = client.getDatabase("sample_restaurants")
val collection = database.getCollection<Restaurant>("restaurants")
// Inserts restaurants into the collection
fun insertRestaurantsInTransaction(session: ClientSession) {
// Inserts restaurants within the transaction
collection.insertOne(
session,
Restaurant("Kotlin Sync Pizza", "Pizza")
)
collection.insertOne(
session,
Restaurant("Kotlin Sync Burger", "Burger")
)
}
// Starts a client session
client.startSession().use { session ->
try {
// Sets transaction options
val txnOptions = TransactionOptions.builder()
.readConcern(ReadConcern.LOCAL)
.writeConcern(WriteConcern.MAJORITY)
.build()
// Uses the withTransaction method to start a transaction and run the given function
session.withTransaction({
insertRestaurantsInTransaction(session)
println("Transaction succeeded")
}, txnOptions)
} catch (e: Exception) {
println("Transaction failed: ${e.message}")
}
}
// Closes the MongoClient
client.close()

如果需要更好地控制事务,可以使用startTransaction()方法。您可以将此方法与上一节中描述的commitTransaction()abortTransaction()方法结合使用,以手动管理事务生命周期。

要了解有关本指南中提到的概念的更多信息,请参阅服务器手册中的以下页面:

要了解有关 ACID 合规性的更多信息,请参阅什么是数据库管理系统中的 ACID 属性? MongoDB 网站上的文章。

要了解有关本指南中讨论的任何类型或方法的更多信息,请参阅以下 API 文档:

后退

批量写入操作