首页 > 解决方案 > 使用事务时对 MongoDB 服务器进行了多少次往返?

问题描述

我想知道在使用事务 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));

“插入操作”是堆叠起来并在一次往返中发送到服务器,还是实际上对服务器进行了两次调用(或更多?)?

标签: javamongodbtransactionsmongo-javamongo-java-driver

解决方案


每个插入单独发送。您可以一起使用批量写入批量写入操作。

最后的提交也是一个单独的操作。


推荐阅读