【发布时间】:2020-07-15 07:13:27
【问题描述】:
我想知道在使用事务 MongoDB 时对服务器进行了多少次往返?例如,如果 Java 驱动程序是这样使用的:
ClientSession clientSession = client.startSession();
TransactionOptions txnOptions = TransactionOptions.builder()
.readPreference(ReadPreference.primary())
.readConcern(ReadConcern.LOCAL)
.writeConcern(WriteConcern.MAJORITY)
.build();
TransactionBody txnBody = new TransactionBody<String>() {
public String execute() {
MongoCollection<Document> coll1 = client.getDatabase("mydb1").getCollection("foo");
MongoCollection<Document> coll2 = client.getDatabase("mydb2").getCollection("bar");
coll1.insertOne(clientSession, new Document("abc", 1));
coll2.insertOne(clientSession, new Document("xyz", 999));
return "Inserted into collections in different databases";
}
};
try {
clientSession.withTransaction(txnBody, txnOptions);
} catch (RuntimeException e) {
// some error handling
} finally {
clientSession.close();
}
在这种情况下,两个文档存储在一个事务中:
coll1.insertOne(clientSession, new Document("abc", 1));
coll2.insertOne(clientSession, new Document("xyz", 999));
“插入操作”是堆叠起来并在一次往返中发送到服务器,还是实际上对服务器进行了两次(或更多?)调用?
【问题讨论】:
标签: java mongodb transactions mongo-java mongo-java-driver