【问题标题】:How many roundtrips are made to a MongoDB server when using transactions?使用事务时对 MongoDB 服务器进行了多少次往返?
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-11
      • 2016-09-17
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      相关资源
      最近更新 更多